How to get content of httpWebresponse in proper string form? - c#

Sometimes I am getting kind of garbled response from several web sites.
Here is my code:
Stream responseStream = response.GetResponseStream();
buffer = new Byte[256];//
int bytesRead;
while ((bytesRead = responseStream.Read(buffer, 0, buffer.Length)) > 0)
{
outStream.Write(buffer, 0, bytesRead);
//resp=resp+ .UTF8.GetString(buffer, 0, bytesRead);
resp=resp + Encoding.ASCII.GetString(buffer); //resp is string
}
when I request from www.google.co.in I get following characters in resp string:
?\b\0\0\0\0\0??}y?F?????????Z??????{7m???oX?\r?Y???33??d;y????n?0?
How should I overcome this problem? Is it related to encoding?

The response I received was GZip-compressed, so I just decompressed the response stream as shown below:
Stream responseStream = response.GetResponseStream();
responseStream = new GZipStream(responseStream, CompressionMode.Decompress);
now one can read the stream using the code I provided above.
#Kalyan Thanks for your help!!!

Refer to How to use the GetResponseStream method in C# and also Usage of HttpWebResponse and HttpWebRequest for getting an idea about reading contents from HttpWebResponse. Hope it will help you.

Related

C# Stream.CanSeek property, This Stream Doesn't Support Seeking

Me and my friend are trying to send http request that we received from the client
listener.Prefixes.Add("http://localhost:3294/discord/");
listener.Start();
Console.WriteLine("Listening...");
HttpListenerContext context = listener.GetContext();
Stream body = context.Request.InputStream;
Encoding encoding = context.Request.ContentEncoding;
StreamReader reader = new StreamReader(body, encoding);
if (body != null)
{
byte[] buffer = new byte[body.Length];
body.Read(buffer, 0, (int)body.Length);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://discord.com/api/webhooks/818198824439004692/jfe2zN93Ca0VOVry0uIBe6xvmx74tYP9QdaEFH--sDMSscKXcgxAYvlu3RSYwb32oZra");
request.Method = "POST";
request.ContentType = context.Response.ContentType;
request.ContentLength = body.Length;
Stream newStream = request.GetRequestStream();
newStream.Write(buffer, 0, buffer.Length);
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
}
but I am getting an error System.NotSupportedException: 'This stream does not support seek operations.' when I try accessing body.Length
and I noticed there is CanSeek property in Stream class but it is has only get.
Is there a way to fix this?
You can't change a non-seekable stream to magically become seekable - in this case, the stream is the set of bytes arriving over the network (perhaps after some TLS/etc work). If you need the data to be seekable, you'll need to buffer (copy) it somewhere else (often a MemoryStream), and seek on that. The preferred option, however, is usually to remove the need to seek the data in the first place.

Building Json Response through httpListener in C#

How can I send Json response by using httpListener class. I have tried some approach but got no luck. I am able to send html and also json as HTML. But not proper json data like webAPI. Here is my piece of code.
HttpListenerResponse response = context.Response;
// Construct a response.
string responseString = //"<HTML><BODY>"+
ObjToJsonConverter(status);//+ "</BODY></HTML>";
// Get a response stream and write the response to it.
byte[] buffer = new byte[] { };
response.ContentType = "Application/json";
buffer = Encoding.ASCII.GetBytes(responseString);
response.ContentLength64 = buffer.Length;
System.IO.Stream output = response.OutputStream;
output.Write(buffer, 0, buffer.Length);
output.Close();
// listener.Stop();
}
}
private static string ObjToJsonConverter(Status obj)
{
return "{\"statusText\":\""+obj.StatusText+",\"statusType\":\""+obj.StatusType+"\"}";
}
which I have tried. I tried to convert my object into jsonstring (above code).But problem of this approach is, response is rendering in chrome but in IE it is downloaded as file.
any help would be appreciated.

HttpWebRequest partially fails to get data

I have this code, calling this sample API call of the game Guild Wars 2
HttpWebRequest request = HttpWebRequest.Create("https://api.guildwars2.com/v1/events.json?world_id=1001") as HttpWebRequest;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
byte[] bytes = new byte[response.ContentLength];
Stream stream = response.GetResponseStream();
stream.Read(bytes, 0, bytes.Length);
string result = Encoding.Default.GetString(bytes);
It is a sample call to the official Guild Wars 2 API and is supposed to return a list of events and their status in JSON format.
If you call the address in a browser and paste the data into a text editor, it gives a correct JSON string, of a little more than 300 kb.
However, when called by this code and, looking at the resulting byte array, the first 3800-3900 bytes are correctly filled (the number varies slightly from call to call), but the rest is all zero.
The response.ContentLength indicates the correct length of the stream, a little more than 300k, and testing with stream.ReadByte() tells me the stream does deliver those 300k, it's just zeroes after that 3850 byte mark.
Is there an error in my code, or what could cause this problem? Could I call the API in another way to get the correct, full response?
The Read operation on a stream returns the number of bytes actually read. You should keep calling stream.Read() until it returns 0. The data simply has not arrived yet.
The reason Read won't block is that some applications may already begin processing the partial data.
You could use the following code:
HttpWebRequest request = HttpWebRequest.Create("https://api.guildwars2.com/v1/events.json?world_id=1001") as HttpWebRequest;
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
byte[] bytes;
using (Stream stream = response.GetResponseStream())
using (MemoryStream buffer = new MemoryStream((int)response.ContentLength))
{
byte[] chunk = new byte[4096];
int bytesRead;
while ((bytesRead = stream.Read(chunk, 0, chunk.Length)) > 0)
{
buffer.Write(chunk, 0, bytesRead);
}
bytes = buffer.ToArray();
}

Making Synchronous xmlhttp request in code behind

I am attempting to send XML to a URL and read the response, but the response is coming back empty every time. I think this is because its being processed Asynchronously and so the receiving code hasn't had a chance to complete by the time I read the response. In Javascrpt I would use
xmlhttp.Open("POST", url, false);
to send a request Synchronously. How can I achieve it in C#?
My code is currently
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
objRequest.Credentials = CredentialCache.DefaultCredentials;
objRequest.Method = "POST";
objRequest.ContentType = "text/xml";
Stream dataStream = objRequest.GetRequestStream();
byte[] bytes = new byte[UpliftJobXMLString.Length * sizeof(char)];
System.Buffer.BlockCopy(UpliftJobXMLString.ToCharArray(), 0, bytes, 0, bytes.Length);
dataStream.Write(bytes, 0, bytes.Length);
dataStream.Close();
HttpWebResponse response = (HttpWebResponse)objRequest.GetResponse();
System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream());
string respString = System.Web.HttpUtility.HtmlDecode(sr.ReadToEnd()); //always empty
Thanks
I'm fairly certain that this is not an async issue. Have you checked what sr.ReadToEnd() returns before the HtmlDecode?
Furthermore, you should check that the server is returning what you're expecting for it to return. Check the response StatusCode and StatusDescription. If your server is throwing an internal server exception (500) or something similar, the response string you read would come up empty as the content of the response would not be sent by the server in the first place.
I don't think your problem is related to sync/async operations. Your code to convert the string to byte array
byte[] bytes = new byte[UpliftJobXMLString.Length * sizeof(char)];
System.Buffer.BlockCopy(UpliftJobXMLString.ToCharArray(), 0, bytes, 0, bytes.Length);
is similar to Unicode encoding(2 bytes per char).
See the differences among encodings
string UpliftJobXMLString = "abcÜ";
byte[] bytesASCII = Encoding.ASCII.GetBytes(UpliftJobXMLString);
byte[] bytesUTF8 = Encoding.UTF8.GetBytes(UpliftJobXMLString);
byte[] bytesUnicode = Encoding.Unicode.GetBytes(UpliftJobXMLString);
Therefore, either set the content-encoding to unicode or use another encoding. For ex;
objRequest.ContentType = "text/xml; charset=utf-8";

Using REST PUT in C#

I am working with a REST API and I am trying to do a PUT method to it. I found this code I was going to give a try:
static void Main()
{
string xml = "<xml>...</xml>";
byte[] arr = System.Text.Encoding.UTF8.GetBytes(xml);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost/");
request.Method = "PUT";
request.ContentType = "text/xml";
request.ContentLength = arr.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(arr, 0, arr.Length);
dataStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string returnString = response.StatusCode.ToString();
Console.WriteLine(returnString);
}
One thing I want to do if possible, and can't seem to find anything about it. I would like to pass the data of text fields so, txtEmail.Text, txtFirstName.Text, etc. Is this possible? If, so how would I go about doing this? Does this code look like it would work? Unfortunately the API I'm working with has very very little documentation. Thanks!
The code lines
Stream dataStream = request.GetRequestStream();
dataStream.Write(arr, 0, arr.Length);
dataStream.Close();
do write something to the remote website. The request stream is the way to provide data to the server, so you would create a string / object that you write to the stream to transfer to the server. In your example <xml>...</xml> is sent to the server.

Categories

Resources