I'm making a HttpWebRequest to a server. This is in JSON. Now, the response is encoded and looks like this:
�\b\0\0\0\0\0\0��A� #ѻ�U�0l�u�\v�v�...
I can see that my request succeeded in Fiddler. And I can see the response of the server is the right one. But, also in fiddler it requires me to decode the answer first.
I have no idea how to decode this in C#.
Here is a bit of sample code that should do exactly what you want. BatchCollection in my case is my own object that maps to the JSON and so it can be mapped after its de-compressed.
var request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.Headers = headers;
request.Headers.Add("Content-Encoding", "gzip");
request.AutomaticDecompression = DecompressionMethods.GZip;
request.ContentType = "application/json";
var json = JsonConvert.SerializeObject(batchCollection);
using (Stream requestStream = request.GetRequestStream())
{
var buffer = Encoding.UTF8.GetBytes(json);
using (GZipStream compressionStream = new GZipStream(requestStream, CompressionMode.Compress, true))
{
compressionStream.Write(buffer, 0, buffer.Length);
}
}
var response = (HttpWebResponse)request.GetResponse();
BatchCollection batchOut = null;
using (Stream responseStream = response.GetResponseStream())
{
var reader = new StreamReader(responseStream);
var jsonOut = reader.ReadToEnd();
reader.Close();
batchOut = JsonConvert.DeserializeObject<BatchCollection>(jsonOut);
}
return batchOut;
Related
I am trying to call API from windows forms its going in timeout. but its working fine from POSTMAN app.
I am using below code for calling web API from windows app.
public string ReadXMLResponse(string strrequestxml, string strTallyServer1)
{
string URL = strTallyServer1;
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(URL);
myHttpWebRequest.Accept = "application/xml";
myHttpWebRequest.ContentType = "application/xml";
myHttpWebRequest.Timeout = 60000;
string method = "POST";
myHttpWebRequest.Method = method;
if (method == "POST")
{
using (var streamWriter = new StreamWriter(myHttpWebRequest.GetRequestStream()))
{
streamWriter.Write(strrequestxml);
streamWriter.Flush();
}
}
HttpWebResponse myHttpWebResponse = (HttpWebResponse)myHttpWebRequest.GetResponse();
using (var streamReader = new StreamReader(myHttpWebResponse.GetResponseStream()))
{
var streamRead = streamReader.ReadToEnd().Trim();
return streamRead;
}
return "";
}
I had the same code and the same problem. It was driving me crazy till I found something on one of Microsoft blogs. Tried to google the original page but I couldn't find it.
WebRequest request = WebRequest.Create("URL");
request.Method = "POST";
var postData = string.Format(dataFormnat, Uri.EscapeDataString(data.Serialize()));
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse response = request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
reader.Close();
dataStream.Close();
response.Close();
I'm trying to login to this website here: https://freebitco.in/
So I set up a web request like so:
var request = (HttpWebRequest)WebRequest.Create("https://freebitco.in");
var postdata = "op=login&btc_address=BTCADDRESS&password=PASSWORD";
var data = Encoding.ASCII.GetBytes(postdata);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length; //1PkhThc9hCXpdvcThtwX3SzbfmTzDFxL1h:bigken <= BTC Login
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
MessageBox.Show(responseString);
The messagebox returns to me nothing though, blank. I'm not sure why this is happening so I was hoping someone could shed some light on this? I've also tried using a Web Client, and it gave me the same result. Thank you guys.
EDIT: Here's the Fiddler Raw data: http://pastebin.com/WUEvq6D5
Edit 2: Tried encoding the POST data and now it returns the login page
Updated Code:
var request = (HttpWebRequest)WebRequest.Create("https://freebitco.in");
var postdata = "op=login&btc_address=ADDRESS&password=PASS";
var encoded_data = HttpUtility.UrlEncode(postdata);
var data = Encoding.ASCII.GetBytes(encoded_data);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
using (var stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
var response = (HttpWebResponse)request.GetResponse();
var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
What I have to do is that I have to post JSON data in given URL
Where my JSON looks like
{
"trip_title":"My Hotel Booking",
"traveler_info":{
"first_name":"Edward",
"middle_name":"",
"last_name":"Cullen",
"phone":{
"country_code":"1",
"area_code":"425",
"number":"6795089"
},
"email":"asdv#gmail.com"
},
"billing_info":{
"credit_card":{
"card_number":"47135821",
"card_type":"Visa",
"card_security_code":"123",
"expiration_month":"09",
"expiration_year":"2017"
},
"first_name":"Edward",
"last_name":"Cullen",
"billing_address":{
"street1":"Expedia Inc",
"street2":"108th Ave NE",
"suite":"333",
"city":"Bellevue",
"state":"WA",
"country":"USA",
"zipcode":"98004"
},
"phone":{
"country_code":"1",
"area_code":"425",
"number":"782"
}
},
"marketing_code":""
}
And my function
string message = "URL";
_body="JSON DATA";
HttpWebRequest request = HttpWebRequest.Create(message) as HttpWebRequest;
if (!string.IsNullOrEmpty(_body))
{
request.ContentType = "text/json";
request.Method = "POST";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(_body);
streamWriter.Flush();
streamWriter.Close();
}
}
using (HttpWebResponse webresponse = request.GetResponse() as HttpWebResponse)
{
using (StreamReader reader = new StreamReader(webresponse.GetResponseStream()))
{
string response = reader.ReadToEnd();
}
}
And when I am posting it; I am getting an error
"The remote server returned an error: (415) Unsupported Media Type."
Anybody have idea about it; where I am mistaking?
Try this:
request.ContentType = "application/json"
For WebAPI >> If you are calling this POST method from fiddler, just add this below line in the header.
Content-Type: application/json
As answered by others the issue is with the ContentType. Should be 'application/json'.
Here is a sample with the old WebRequest
var parameters = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
var req = WebRequest.Create(uri);
req.Method = "POST";
req.ContentType = "application/json";
byte[] bytes = Encoding.ASCII.GetBytes(parameters);
req.ContentLength = bytes.Length;
using (var os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
os.Close();
}
var stream = req.GetResponse().GetResponseStream();
if (stream != null)
using (stream)
using (var sr = new StreamReader(stream))
{
return sr.ReadToEnd().Trim();
}
return "Response was null";
I renamed my project and updated all of the namespaces to correlate after which I got this exact same message.
I realized that I had not updated the namespaces in the web.config (name and contract):
<system.serviceModel>
<services>
<service name="X.Y.Z.Authentication" behaviorConfiguration="ServiceBehaviour">
<endpoint address="" binding="webHttpBinding" contract="X.Y.Z.IAuthentication" behaviorConfiguration="web" bindingConfiguration="defaultRestJsonp"></endpoint>
</service>
</...>
</..>
Hope this helps anyone reading this.
Im not 100% sure but I guess you have to send the text as a byteArray, try this:
req = (HttpWebRequest)HttpWebRequest.Create(uri);
req.CookieContainer = cookieContainer;
req.Method = "POST";
req.ContentType = "text/json";
byte[] byteArray2 = Encoding.ASCII.GetBytes(body);
req.ContentLength = byteArray2.Length;
Stream newStream = req.GetRequestStream();
newStream.Write(byteArray2, 0, byteArray2.Length);
newStream.Close();
this is sample of a code i created for web api function that accepts json data
string Serialized = JsonConvert.SerializeObject(jsonData);
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpContent content = new StringContent(Serialized, Encoding.Unicode, "application/json");
var response = await client.PostAsync("http://localhost:1234", content);
}
Serialize the data you want to pass and encode it. Also, mention
req.ContentType = "application/json";
"martin " code works.
LoginInfo obj = new LoginInfo();
obj.username = uname;
obj.password = pwd;
var parameters = Newtonsoft.Json.JsonConvert.SerializeObject(obj);
var req = WebRequest.Create(uri);
req.Method = "POST";
req.ContentType = "application/json";
byte[] bytes = Encoding.ASCII.GetBytes(parameters);
req.ContentLength = bytes.Length;
using (var os = req.GetRequestStream())
{
os.Write(bytes, 0, bytes.Length);
os.Close();
}
var stream = req.GetResponse().GetResponseStream();
if (stream != null)
using (stream)
using (var sr = new StreamReader(stream))
{
return sr.ReadToEnd().Trim();
}
Here's my code for Request and Response.
System.IO.MemoryStream xmlStream = null;
HttpWebRequest HttpReq = (HttpWebRequest)WebRequest.Create(url);
xmlStream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(format));
byte[] buf2 = xmlStream.ToArray();
System.Text.UTF8Encoding UTF8Enc = new System.Text.UTF8Encoding();
string s = UTF8Enc.GetString(buf2);
string sPost = "XMLData=" + System.Web.HttpUtility.UrlDecode(s);
byte[] bPostData = UTF8Enc.GetBytes(sPost);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.ContentType = "application/x-www-form-urlencoded";
HttpReq.Timeout = 30000;
request.Method = "POST";
request.KeepAlive = true;
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(bPostData, 0, bPostData.Length);
requestStream.Close();
}
string responseString = "";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
responseString = sr.ReadToEnd();
}
No part of this code crashes. The "format" string is the one with XML in it. By the end when you try to see what's in the responseString, it's an empty string. I am supposed to see the XML sent back to me from the URL. Is there something missing in this code?
I would recommend a simplification of this messy code:
using (var client = new WebClient())
{
var values = new NameValueCollection
{
{ "XMLData", format }
};
byte[] resultBuffer = client.UploadValues(url, values);
string result = Encoding.UTF8.GetString(resultBuffer);
}
and if you wanted to upload the XML directly in the POST body you shouldn't be using application/x-www-form-urlencoded as content type. You probably should specify the correct content type, like this:
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "text/xml";
var data = Encoding.UTF8.GetBytes(format);
byte[] resultBuffer = client.UploadData(url, data);
string result = Encoding.UTF8.GetString(resultBuffer);
}
HttpWebRequest request = WebRequest.Create("http://google.com") as HttpWebRequest;
request.Accept = "application/xrds+xml";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
WebHeaderCollection header = response.Headers;
Here google returns text. How to read it?
Your "application/xrds+xml" was giving me issues, I was receiving a Content-Length of 0 (no response).
After removing that, you can access the response using response.GetResponseStream().
HttpWebRequest request = WebRequest.Create("http://google.com") as HttpWebRequest;
//request.Accept = "application/xrds+xml";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
WebHeaderCollection header = response.Headers;
var encoding = ASCIIEncoding.ASCII;
using (var reader = new System.IO.StreamReader(response.GetResponseStream(), encoding))
{
string responseText = reader.ReadToEnd();
}
The accepted answer does not correctly dispose the WebResponse or decode the text. Also, there's a new way to do this in .NET 4.5.
To perform an HTTP GET and read the response text, do the following.
.NET 1.1 ‒ 4.0
public static string GetResponseText(string address)
{
var request = (HttpWebRequest)WebRequest.Create(address);
using (var response = (HttpWebResponse)request.GetResponse())
{
var encoding = Encoding.GetEncoding(response.CharacterSet);
using (var responseStream = response.GetResponseStream())
using (var reader = new StreamReader(responseStream, encoding))
return reader.ReadToEnd();
}
}
.NET 4.5
private static readonly HttpClient httpClient = new HttpClient();
public static async Task<string> GetResponseText(string address)
{
return await httpClient.GetStringAsync(address);
}
I've just tried that myself, and it gave me a 200 OK response, but no content - the content length was 0. Are you sure it's giving you content? Anyway, I'll assume that you've really got content.
Getting actual text back relies on knowing the encoding, which can be tricky. It should be in the Content-Type header, but then you've got to parse it etc.
However, if this is actually XML (e.g. from "http://google.com/xrds/xrds.xml"), it's a lot easier. Just load the XML into memory, e.g. via LINQ to XML. For example:
using System;
using System.IO;
using System.Net;
using System.Xml.Linq;
using System.Web;
class Test
{
static void Main()
{
string url = "http://google.com/xrds/xrds.xml";
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(url);
XDocument doc;
using (WebResponse response = request.GetResponse())
{
using (Stream stream = response.GetResponseStream())
{
doc = XDocument.Load(stream);
}
}
// Now do whatever you want with doc here
Console.WriteLine(doc);
}
}
If the content is XML, getting the result into an XML object model (whether it's XDocument, XmlDocument or XmlReader) is likely to be more valuable than having the plain text.
This article gives a good overview of using the HttpWebResponse object:How to use HttpWebResponse
Relevant bits below:
HttpWebResponse webresponse;
webresponse = (HttpWebResponse)webrequest.GetResponse();
Encoding enc = System.Text.Encoding.GetEncoding(1252);
StreamReader loResponseStream = new StreamReader(webresponse.GetResponseStream(),enc);
string Response = loResponseStream.ReadToEnd();
loResponseStream.Close();
webresponse.Close();
return Response;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://www.google.com");
request.Method = "GET";
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string strResponse = reader.ReadToEnd();
response.GetResponseStream() should be used to return the response stream. And don't forget to close the Stream and Response objects.
If you http request is Post and request.Accept = "application/x-www-form-urlencoded";
then i think you can to get text of respone by code bellow:
var contentEncoding = response.Headers["content-encoding"];
if (contentEncoding != null && contentEncoding.Contains("gzip")) // cause httphandler only request gzip
{
// using gzip stream reader
using (var responseStreamReader = new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress)))
{
strResponse = responseStreamReader.ReadToEnd();
}
}
else
{
// using ordinary stream reader
using (var responseStreamReader = new StreamReader(response.GetResponseStream()))
{
strResponse = responseStreamReader.ReadToEnd();
}
}