For some reason I cant use GetRequestStream or GetResponse in silverlight comes up underlined :S not sure what to use? I am trying to connect to my web service here is where I get the error,
string uri = "http://localhost:8002/Service/Customer";
StringBuilder sb = new StringBuilder();
sb.Append("<Customer>");
sb.AppendLine("<FirstName>" + this.textBox1.Text + "</FirstName>");
sb.AppendLine("<LastName>" + this.textBox2.Text + "</LastName>");
sb.AppendLine("</Customer>");
string NewCustomer = sb.ToString();
byte[] arr = Encoding.UTF8.GetBytes(NewCustomer );
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
req.Method = "POST";
req.ContentType = "application/xml";
req.ContentLength = arr.Length;
Stream reqStrm = req.GetRequestStream();// error here GetRequestStream
reqStrm.Write(arr, 0, arr.Length);
reqStrm.Close();
HttpWebResponse resp = (HttpWebResponse)req.GetResponse(); //error here GetRequestStream
MessageBox.Show("Staff Creation: Status " + resp.StatusDescription);
reqStrm.Close();
resp.Close();
Does anyone have a workaround?
Silverlight only supports the Asynchronous network access. There are no synchronous GetRequestStream and GetResponse methods in Silverlight. You will need to use the asynchronous methods BeginGetRequestStream/EndGetRequestStream and BeginGetResponse/EndGetResponse.
More importantly you will need to get up to speed in how to do things asynchronously in general. For example something will be calling your above code and expect that after it is complete certain changes will have happpened. In the asynchronous world that will not be true, the code will return quickly and something will happen later.
Related
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 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.
Im trying to make a small login system but i have this problem that when the project runs on VS2010 it says :
The remote server returned an error: (405) Method Not Allowed.
Heres my code:
//Our URL
string uri = "https://************************/ValidateUsername";
//Our postvars
byte[] buffer = Encoding.ASCII.GetBytes( "username=user" );
//Initialization
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Accept = "application/json;odata=verbose";
request.Headers.Add("Language", "es-MX");
request.Headers.Add("Application", "-------------------");
request.Headers.Add("Version", "1.0");
//Our method is POST, otherway buffer would be useless
request.Method = "POST";
//We use form contentType, for the postvars
request.ContentType = "application/x-www-form-urlencoded";
//The lenght of the content its set by postvars (buffer) lenght
request.ContentLength = buffer.Length;
//We open a stream for writing the postvars
Stream PostData = request.GetRequestStream();
//Now we write, and afterwards, we close.
PostData.Write(buffer, 0, buffer.Length);
When i hover the pointer over "PostData" and then i go to the length and position attributes, i can read :
Length = 'PostData.Length' threw an exception of type 'System.NotSupportedException'
base {System.SystemException} = {"This stream does not support seek operations."}
im not sure if this is the real problem, but im trying to give the mos of information possible.
PostData.Close();
//Get the response Handle
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
//lets show info about the response
Console.WriteLine("Estatus de la respuesta:" + response.StatusCode);
Console.WriteLine("Servidor : " + response.Server);
//Now we read the response (the string), and output it
//Stream answer = response.GetResponseStream();
//StreamReader _answer = new StreamReader(answer);
//Console.WriteLine("Respuesta: " + _answer.ReadToEnd());
At some forum i read that maybe the "_answer.ReadToEnd()" could be the problem but even thought i commented , the problem still arises.
Im doing this so i can try it later on windows phone, dont know if im wasting my time , because they are not related.
I hope someone can help. Thanks in advance.
I've got a problem with creating an HTTP post request in .NET. When I do this request in ruby it does work.
When doing the request in .NET I get following error:
<h1>FOXISAPI call failed</h1><p><b>Progid is:</b> carejobs.carejobs
<p><b>Method is:</b> importvacature/
<p><b>Parameters are:</b>
<p><b> parameters are:</b> vacature.deelnemernr=478
</b><p><b>GetIDsOfNames failed with err code 80020006: Unknown name.
</b>
Does anyone knows how to fix this?
Ruby:
require 'net/http'
url = URI.parse('http://www.carejobs.be/scripts/foxisapi.dll/carejobs.carejobs.importvacature')
post_args = {
'vacature.deelnemernr' => '478',
}
resp, data = Net::HTTP.post_form(url, post_args)
print resp
print data
C#:
Uri address = new Uri(url);
// Create the web request
HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest;
// Set type to POST
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
// Create the data we want to send
StringBuilder data = new StringBuilder();
data.Append("vacature.deelnemernr=" + HttpUtility.UrlEncode("478"));
// Create a byte array of the data we want to send
byte[] byteData = UTF8Encoding.UTF8.GetBytes(data.ToString());
// Set the content length in the request headers
request.ContentLength = byteData.Length;
// Write data
using (Stream postStream = request.GetRequestStream())
{
postStream.Write(byteData, 0, byteData.Length);
}
// Get response
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
// Get the response stream
StreamReader reader = new StreamReader(response.GetResponseStream());
// Console application output
result = reader.ReadToEnd();
}
return result;
Don't you need the ? after the URL in order to do a post with parameters? I think that Ruby hides this behind the scenes.
I found the problem! The url variable in the C# code was "http://www.carejobs.be/scripts/foxisapi.dll/carejobs.carejobs.importvacature/"
It had to be "http://www.carejobs.be/scripts/foxisapi.dll/carejobs.carejobs.importvacature" without the backslash.