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);
Related
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'm trying to do a WebRequest to a site from a Windows Phone Application.
But is vry important for me to also get the response from the server.
Here is my code:
Uri requestUri = new Uri(string.Format("http://localhost:8099/hello/{0}", metodo));
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUri);
httpWebRequest.ContentType = "application/xml; charset=utf-8";
httpWebRequest.Method = "POST";
using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream,
httpWebRequest.EndGetRequestStream, null))
{
string xml = "<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">Ahri</string>";
byte[] xmlAsBytes = Encoding.UTF8.GetBytes(xml);
await stream.WriteAsync(xmlAsBytes, 0, xmlAsBytes.Length);
}
Unfortunatelly, I have no idea of how I could get the response from the server.
Does anyone have an idea?
Thanks in advance.
Thanks to #max I found the solution and wanted to share it above.
Here is how my code looks like:
string xml = "<string xmlns=\"http://schemas.microsoft.com/2003/10/Serialization/\">Claor</string>";
Uri requestUri = new Uri(string.Format("http://localhost:8099/hello/{0}", metodo));
string responseFromServer = "no response";
HttpWebRequest httpWebRequest = HttpWebRequest.Create(requestUri) as HttpWebRequest;
httpWebRequest.ContentType = "application/xml; charset=utf-8";
httpWebRequest.Method = "POST";
using (Stream requestStream = await httpWebRequest.GetRequestStreamAsync())
{
byte[] xmlAsBytes = Encoding.UTF8.GetBytes(xml);
await requestStream.WriteAsync(xmlAsBytes, 0, xmlAsBytes.Length);
}
WebResponse webResponse = await httpWebRequest.GetResponseAsync();
using (var reader = new StreamReader(webResponse.GetResponseStream()))
{
responseFromServer = reader.ReadToEnd();
}
I hope it will help someone in the future.
This is very common question for people new in windows phone app
development. There are several sites which gives tutorials for the
same but I would want to give small answer here.
In windows phone 8 xaml/runtime you can do it by using HttpWebRequest or a WebClient.
Basically WebClient is a wraper around HttpWebRequest.
If you have a small request to make then user HttpWebRequest. It goes like this
HttpWebRequest request = HttpWebRequest.Create(requestURI) as HttpWebRequest;
WebResponse response = await request.GetResponseAsync();
using (var reader = new StreamReader(response.GetResponseStream()))
{
string responseContent = reader.ReadToEnd();
// Do anything with you content. Convert it to xml, json or anything.
}
Although this is a get request and i see that you want to do a post request, you have to modify a few steps to achieve that.
Visit this place for post request.
If you want windows phone tutorials, you can go here. He writes awesome tuts.
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.
i am facing a problem where i try to communicate with a Ruby API from a C# application.
I need to POST some JSON data, with the parameter name "data" but the API return me: '!! Unexpected error while processing request: invalid %-encoding'.
I tried with Content-Type set to 'application/json' and 'application/x-www-form-urlencoded; charset=utf-8'.
My POST data look like this 'data=some_json_string'.
I figure i should escape the json string, so if it is my problem, how to do it with .NET without using a 3rd party library?
Code:
byte[] data = System.Text.ASCIIEncoding.UTF8.GetBytes(sdata);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url, UriKind.Absolute));
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded; charset=utf-8";
request.ContentLength = data.Length;
Stream reqStream = request.GetRequestStream();
// Send the data.
reqStream.Write(data, 0, data.Length);
reqStream.Close();
Thanks in advance!
Presuming the string sdata coming in is already in JSON format you could do:
using (WebClient wc = new WebClient())
{
string uri = "http://www.somewhere.com/somemethod";
string parameters = "data=" + Uri.EscapeDataString(sdata);
wc.Headers["Content-type"] = "application/x-www-form-urlencoded";
string result = wc.UploadString(uri, parameters);
}
Depending on the consuming service it may need the Content-type set to application/json?
I am sending an HTTP post request using HTTPWebRequest to an URL. I am sending the post data using multipart/form-data content type along with the content length of the body. However, on the server side, I am unable to retrieve the body. I can only see the headers sent. The content length of the body I sent also matches.
Why am I not able to retrieve the body.
The request method looks like this:
public void Reset(string originalFileData, string uploadLocation)
{
TcpClient client = new TcpClient();
IPEndPoint serverEndPoint = new IPEndPoint(IPAddress.Parse(Server), portNo);
client.Connect(serverEndPoint);
string responseContent;
string serverUrl = "http://" + Server + ":" + portNo + "/abc.aspx" + "?uplvar=" + uploadLocation;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(serverUrl);
request.ContentType = "multipart/form-data";
request.Method = "POST";
request.ServicePoint.Expect100Continue = false;
string postData = originalFileData;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
Stream dataStream = request.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
response.Close();
}
Edit: I forgot to mention, I am able to retrieve the body on the first time I send the request, but on any subsequent requests I send, I am not able to retrieve it. I am creating a new connection each time I send a request. So, something might be preventing the request body from being retrieved. I am not sure why.
Try replacing
request.ContentType = "multipart/form-data";
with
request.ContentType = "application/x-www-form-urlencoded";
or check this SO answer for code which works with multipart/formdata.