I am trying to get the access token from MNS for Push notifications and the WebRequest.GetRequestStreamAsync() method timesout each time. Any suggestions?
Reference: http://msdn.microsoft.com/en-us/library/windows/apps/hh913756.aspx
Below is the code I use
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.Create("https://login.live.com/accesstoken.srf");
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
string postString = String.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=notify.windows.com",
SID,
SECRET_KEY);
byte[] data = Encoding.UTF8.GetBytes(postString);
Stream newStream = await webRequest.GetRequestStreamAsync();
newStream.Write(data, 0, data.Length);
Try rewriting it like this and see if it makes a difference. I've sometimes had problems with HttpWebRequest where WebRequest worked fine. Also make sure you close your streams.
WebRequest webRequest = WebRequest.Create("https://login.live.com/accesstoken.srf");
webRequest.Method = "POST";
webRequest.ContentType = "application/x-www-form-urlencoded";
string postString = String.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=notify.windows.com",
SID,
SECRET_KEY);
byte[] data = Encoding.UTF8.GetBytes(postString);
Stream newStream = await webRequest.GetRequestStreamAsync();
newStream.Write(data, 0, data.Length);
newStream.Close();
WebResponse response = webRequest.GetResponse();
StreamReader requestReader = new StreamReader( response.GetResponseStream() );
string webResponse = requestReader.ReadToEnd();
response.Close();
Call .ConfigureAwait(false) on your Async method.
This blog post should explain the why and how.
We had the same problem and it turned out to be a problem in different place than one would originally guess.
You need to .Dispose() or at least .Close() the response that you get from .GetResponseAsync, otherwise the next call to .GetRequestStreamAsync hangs.
It seems that the code behind this holds some limited (rather low) amount of sockets or locks, that disallow further requests to even begin until previous request has completed.
Related
I am trying to send protobuf data via REST from c# winform application. When I use the HTTP request with POST method( as shown in code below) it works perfect and returns "OK" status.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://xxxxx.execute-api.eu-west-1.amazonaws.com/test/input");
request.Headers["Authorization"] = "xxxyyyzzz"
request.Method = "POST";
request.ContentType = "application/octet-stream";
byte[] bytes = System.IO.File.ReadAllBytes("C:\\MyProtobuf.proto");
request.ContentLength = bytes.Length;
Stream requestStream = request.GetRequestStream();
requestStream.Write(bytes, 0, bytes.Length);
HttpWebResponse myHttpWebResponse = (HttpWebResponse)request.GetResponse();
MessageBox.Show(myHttpWebResponse .StatusCode.ToString());
myHttpWebResponse .Close();
But if I simply want to check if website is alive or not using below code it gives me 403. Forbidden error.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("https://xxxxx.execute-api.eu-west-1.amazonaws.com/test/input");
request.Headers["Authorization"] = "xxxyyyzzz";
HttpWebResponse myHttpWebResponse = (HttpWebResponse)request.GetResponse();
MessageBox.Show(myHttpWebResponse .StatusCode.ToString());
myHttpWebResponse .Close();
what could be the possible reason for this error ?
your services serves POST method verb so you must call this service with post method, otherwise you should change your service methods to support get method.
The request gives the following error:
The remote server returned an error: (400) Bad Request.
I cann't find a solution on internet. Does anyone knows how to solve this?
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(#"https://maps.googleapis.com/maps/api/geocode/json");
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
var parameters = string.Format("language={0}&latlng={1}&client={2}&signature={3}", "nl", "51.123456,5.612345", "gme-aa", "******_******=");
byte[] byteArray = Encoding.UTF8.GetBytes(parameters);
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
/*
* Read HttpWeb Response
*/
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string Response = reader.ReadToEnd();
response.Close();
EDIT:
I'm working inside Lowcode platform Outsystems. Outsystems creates the url inside WebRequest.Create() without the paramaters. So, I have access to webRequest object and need to pass the parameters.
You have to use HTTP "GET" Method.
In a GET request, you pass parameters as part of the query string.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create($"https://maps.googleapis.com/maps/api/geocode/json?language=fr&latlng=51.123456,5.612345&key={apiKey}");
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "GET";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
string result = new StreamReader(response.GetResponseStream()).ReadToEnd();
}
According the documentation, the API is expecting a POST method and receiving the parameters in the URL and not the body.
If you are using the OutSystems platform you can use the Consume REST API functionality to easily call the web service without using code. Configure your API like this (you can copy the example JSON from the documentation page above):
I am writing the code as :
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(qry);
request.ContentType = "application/x-www-form-urlencoded";
request.Method = "POST";
request.KeepAlive = false;
request.ContentLength = 0;
byte[] data = Encoding.UTF8.GetBytes(crsAdapterXML.ToString());
request.ContentLength = data.Length;
Stream stream = request.GetRequestStream();
stream.Write(data, 0, data.Length);
stream.Close();
Stream objStream = request.GetResponse().GetResponseStream();
StreamReader objReader = new StreamReader(objStream);
result = Convert.ToString(objReader.ReadLine());
I need to make this call asyncronous. Can anyone help me with this.
Using HttpWebRequest is kinda old school way of doing HTTP requests nowadays.
There are libraries which provide better APIs to do this.
I recommend you to try Microsoft's HttpClient (System.Net.Http) or RestSharp.
There are probably many more but those are the ones I know and didn't have problems with.
Both provide async API so you can asynchronously wait for a response.
I don't have much experience with HttpWebRequest but it seems it also exposes async variations of its methods like GetResponseAsync or GetRequestStreamAsync
I'm creating a application, and in one of it's functionalities I need to send json code over web request.
I use Get, Post, Put and Delete. And I already can create the connection and send and receive data.
But, for every request I should receive json code. Which I believe I am receiving, but I can't read it...
I'l put some code sample so you can see if there is something I can make to read that json code
First the Get request:
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create (this.getURL ());
webRequest.Method = "GET";
webRequest.ContentType = "application/json";
webRequest.Accept = "application/json";
var response = (HttpWebResponse)webRequest.GetResponse ();
var responseString = new StreamReader (response.GetResponseStream ()).ReadToEnd ();
webRequest.Abort();
return JArray.Parse (responseString);
This is the only case where I can read the json answer.
Next Post request:
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create (this.getURL ());
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
webRequest.Accept = "application/json";
var data = Encoding.UTF8.GetBytes(request);
webRequest.ContentLength = data.Length;
Stream stream = webRequest.GetRequestStream ();
stream.Write (data, 0, data.Length);
stream.Close ();
var response = (HttpWebResponse)webRequest.GetResponse();
webRequest.Abort();
return (int)response.StatusCode;
In this example I solved my problem using the response code.. which can only be 200, because every other code Is assumed as some exception.
For put and delete will be the same as post.
As I said I need to receive the json code. and not only the response code.
I would be really grateful if you could help-me in this problem.
Thanks to Orel who tried do help.
I got mt problem solved, I will post a sample code for everyone who might need this kind of solution.
My problem actually was very simple.
When I used "POST" in a web request I would create a stream to actually post my data. And then I would try to get my answer from that same stream, when actually I was getting the information I needed In the webRequest var.
HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create (this.getURL ());
webRequest.Method = "POST";
webRequest.ContentType = "application/json";
webRequest.Accept = "application/json";
var data = Encoding.UTF8.GetBytes(request);
webRequest.ContentLength = data.Length;
Stream stream = webRequest.GetRequestStream ();
stream.Write (data, 0, data.Length);
var webResponse = (HttpWebResponse)webRequest.GetResponse();
var responseString = new StreamReader(webResponse.GetResponseStream()).ReadToEnd();
stream.Close ();webRequest.Abort();
return JObject.Parse(responseString);
I'm trying to read the reponse from a webserver using httpwebrequests in C#.
I use the following code:
UriBuilder urib = new UriBuilder();
urib.Host = "wikipedia.com";
HttpWebRequest req = WebRequest.CreateHttp(urib.Uri);
req.KeepAlive = false;
req.Host = "wikipedia.com/";
req.Method = "GET";
HttpWebResponse response = (HttpWebResponse) req.GetResponse();
byte[] buffer = new byte[response.ContentLength];
System.IO.Stream stream = response.GetResponseStream();
stream.Read(buffer, 0, buffer.Length);
Console.WriteLine(System.Text.Encoding.ASCII.GetString(buffer, 0, buffer.Length));
The code does indeed retrieve the correct amount of data (I compared the contentlength used to create the buffer, with the length of the console output, they're the same.
My problem is that the last 80% or so of the response is blank chars. They're all 0x00.
I tested this with several pages, including wikipedia.com and it just cuts off mid-file for some reason.
Have I misunderstood/misused the way to use webrequests or can anyone spot an error here?
Try to use this method:
public static String GetResponseString(Uri url, CookieContainer cc)
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = WebRequestMethods.Http.Get;
request.CookieContainer = cc;
request.AutomaticDecompression = DecompressionMethods.GZip;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
String responseString = reader.ReadToEnd();
response.Close();
return responseString;
}
There are a couple of issues with your code:
Your trying to read the entire response in one go using Stream.Read - that's not what it was designed for. This should be used for more optimal reading e.g. 4KB chunks.
Your reading a HTML response as ASCII encoding - are you sure the page doesn't contain any Unicode characters? I would stick to UTF-8 encoding to be on the safe side (or alternatively read the Content-Type header in the response).
When reading characters from a byte stream (which is what your response is essentially) the recommended approach is to use StreamReader. More specifically, if you want to read the entire stream in one go then use StreamReader.ReadToEnd.
Your code could be shortened to:
HttpWebRequest req = WebRequest.CreateHttp(new Uri("http://wikipedia.org"));
req.Method = WebRequestMethods.Http.Get;
using (var response = (HttpWebResponse)req.GetResponse())
using (var reader = new StreamReader(response.GetResponseStream()))
{
Console.WriteLine(reader.ReadToEnd());
}