I use a WebClient class to nagivate to a website. it returns me a download dialog box to download the output in a json file. Issit possible to read whats in the json file without downloading it? i opened up chrome and pasted the same url and chrome showed me the output in the browser itself.
It depends on the content type and browser, content may be zipped in some instances. Stackoverflow API is one such example.
In these cases you need to set request.AutomaticDecompression. Below code might give you fair idea of understanding and to continue from there.
public string CallRequest(Uri url)
{
var request = WebRequest.Create(url) as HttpWebRequest;
var httpResponse = "";
if (request != null)
{
request.UserAgent = "stackoverflow"; // just example.
request.Accept = "gzip,deflate";
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
using (var response = request.GetResponse() as HttpWebResponse)
{
using (var responseStream = response.GetResponseStream())
{
var reader = new StreamReader(responseStream);
httpResponse = reader.ReadToEnd();
}
}
}
return httpResponse;
}
Just make a request to the link and you will have the JSON in a string:
public static Response MakeRequest(string requestUrl){
try
{
HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
throw new Exception(String.Format(
"Server error (HTTP {0}: {1}).",
response.StatusCode,
response.StatusDescription));
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(Response));
object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
Response jsonResponse
= objResponse as Response;
return jsonResponse;
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
}
Related
I am using Postman to get the response from rest end point, and if I pass wrong data I am getting 400 exception which is very correct as per the logic.
But if I try to call the same web request from C# code(with same wrong parameter), I am getting exception but not the same as I am getting in Postman tool.
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
var httpWebRequest = (HttpWebRequest)WebRequest.Create("https://apiurl");
httpWebRequest.ContentType = "application/json";
httpWebRequest.Headers.Add("Authorization", "Bearer " + token);
httpWebRequest.Method = "POST";
httpWebRequest.UserAgent = ".Net application";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string json = JsonConvert.SerializeObject(obj);//obj is parameter
streamWriter.Write(json);
}
try
{
HttpWebResponse httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var result = streamReader.ReadToEnd();
}
}
catch (WebException e)
{
}
Can I know why I am getting errors differently from postman and C# code
Regards
Anand
Added below code in the exception block and it gave me the same response as Postman
catch(WebException ex)
{
string message = ex.Message;
WebResponse errorResponse = ex.Response;
if (errorResponse != null)
{
using (Stream responseStream = errorResponse.GetResponseStream())
{
StreamReader reader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8"));
message = reader.ReadToEnd();
}
}
}
I've got a web service that returns an http 500 with some diagnostic information in the body of the response.
I'm doing something like
Stream responseStream = null;
WebResponse _Response = null;
Stream responseStream = null;
HttpWebRequest _Request = null;
try
{
_Response = _Request.GetResponse();
responseStream = _Response.GetResponseStream();
}
catch {
//try to view the Request.GetResponse() body here.
}
Since _Request.GetResponse() is returning an http 500 there doesn't seem to be a way to view the response body. According to HTTP 500 Response with Body? this was a known issue in Java 9 years ago. I'm wondering if there's a way to do it in .NET today.
The microsoft docs give a good run down of what HttpWebRequest.GetResponse returns if it fails, you can check it out here https://learn.microsoft.com/en-us/dotnet/api/system.net.httpwebrequest.getresponse?view=netframework-4.8
In your example I believe you need to check for WebException and handle it.
Stream responseStream = null;
WebResponse _Response = null;
Stream responseStream = null;
HttpWebRequest _Request = null;
try
{
_Response = _Request.GetResponse();
responseStream = _Response.GetResponseStream();
}
catch (WebException w)
{
//here you can check the reason for the web exception
WebResponse res = w.Response;
using (Stream s = res.GetResponseStream())
{
StreamReader r= new StreamReader(s);
string exceptionMessage = r.ReadToEnd(); //here is your error info
}
}
catch {
//any other exception
}
I have this code:
public static string Connect(string Uri)
{
try
{
HttpWebRequest connection = WebRequest.Create(requestURI) as HttpWebRequest;
connection.Method = "GET";
string response;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
using (var responseStream = new StreamReader(response.GetResponseStream()))
{
responseText = responseStream.ReadToEnd();
}
return response;
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
If the API return 200 http status the response variable is returned correctly, instead if I have client error 400 or 500 the code fall in exception. I want manage this exception in the try instead fall in the Console.WriteLine, there is a change for do this?
You could do something like this, to minimise duplicated code and handle the exception as close to where it's thrown as possible.
public static string Connect(string Uri)
{
HttpWebRequest connection = WebRequest.Create(requestURI) as HttpWebRequest;
connection.Method = "GET";
string response;
HttpWebResponse response = null;
try
{
response = request.GetResponse() as HttpWebResponse
}
catch (WebException ex)
{
response = ex.Response;
}
using (response)
using (var responseStream = new StreamReader(response.GetResponseStream()))
{
responseText = responseStream.ReadToEnd();
}
return response;
}
I'm trying to get the status code returned from http response, like this:
try
{
HttpWebRequest request = WebRequest.Create(requestURI) as HttpWebRequest;
string text
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
using (var responseStream = new StreamReader(response.GetResponseStream()))
{
text = responseStream.ReadToEnd();
}
var responseHeader = (HttpWebResponse)request.GetResponse();
var status = responseHeader.StatusCode;
}
catch (WebException ex)
{
MessageBox.Show(ex.ToString());
}
the problem is that I get this exception:
System.ObjectDisposedException : "Cannot access to removed object Name: 'System.Net.HttpWebResponse'."}
on this line: var status = responseHeader.StatusCode;
why happean this? I want get the status code and the description
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
will dispose the response after leaving the using block.
So another call to (HttpWebResponse)request.GetResponse(); will throw the exception. Additionally, because it's a web response, you cannot read it twice.
Try this alternative:
HttpWebRequest request = WebRequest.Create(requestURI) as HttpWebRequest;
string text;
HttpStatusCode status;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
using (var responseStream = new StreamReader(response.GetResponseStream()))
{
text = responseStream.ReadToEnd();
status = response.StatusCode;
}
First of all: I know this has been asked over 100 times, but most of these questions were eigher caused by timeout problems, by incorrect Url or by foregetting to close a stream (and belive me, I tried ALL the samples and none of them worked).
So, now to my question: in my Windows Phone app I'm using the HttpWebRequest to POST some data to a php web service. That service should then save the data in some directories, but to simplify it, at the moment, it only echos "hello".
But when I use the following code, I always get a 404 complete with an apache 404 html document. Therefor I think I can exclude the possibility of a timeout. It seems like the request reaches the server, but for some reason, a 404 is returned. But what really makes me be surprised is, if I use a get request, everything works fine. So here is my code:
HttpWebRequest webRequest = (HttpWebRequest)HttpWebRequest.CreateHttp(server + "getfeaturedpicture.php?randomparameter="+ Environment.TickCount);
webRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0";
webRequest.Method = "POST";
webRequest.ContentType = "text/plain; charset=utf-8";
StreamWriter writer = new StreamWriter(await Task.Factory.FromAsync<Stream>(webRequest.BeginGetRequestStream, webRequest.EndGetRequestStream, null));
writer.Write(Encoding.UTF8.GetBytes("filter=" + Uri.EscapeDataString(filterML)));
writer.Close();
webRequest.BeginGetResponse(new AsyncCallback((res) =>
{
string strg = getResponseString(res);
Stator.mainPage.Dispatcher.BeginInvoke(() => { MessageBox.Show(strg); });
}), webRequest);
Although I don't think this is the reason, here's the source of getResponseString:
public static string getResponseString(IAsyncResult asyncResult)
{
HttpWebRequest webRequest = (HttpWebRequest)asyncResult.AsyncState;
HttpWebResponse webResponse;
try
{
webResponse = (HttpWebResponse)webRequest.EndGetResponse(asyncResult);
}
catch (WebException ex)
{
webResponse = ex.Response as HttpWebResponse;
}
MemoryStream tempStream = new MemoryStream();
webResponse.GetResponseStream().CopyTo(tempStream);
tempStream.Position = 0;
webResponse.Close();
return new StreamReader(tempStream).ReadToEnd();
}
This is tested code work fine in Post method with some body. May this gives you an idea.
public void testSend()
{
try
{
string url = "abc.com";
string str = "test";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.ContentType = "text/plain; charset=utf-8";
req.BeginGetRequestStream(SendRequest, req);
}
catch (WebException)
{
}
}
//Get Response and write body
private void SendRequest(IAsyncResult asyncResult)
{
string str = "test";
string Data = "data=" + str;
HttpWebRequest req= (HttpWebRequest)asyncResult.AsyncState;
byte[] postBytes = Encoding.UTF8.GetBytes(Data);
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = postBytes.Length;
Stream requestStream = req.GetRequestStream();
requestStream.Write(postBytes, 0, postBytes.Length);
requestStream.Close();
request.BeginGetResponse(SendResponse, req);
}
//Get Response string
private void SendResponse(IAsyncResult asyncResult)
{
try
{
MemoryStream ms;
HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult);
HttpWebResponse httpResponse = (HttpWebResponse)response;
string _responestring = string.Empty;
using (Stream data = response.GetResponseStream())
using (var reader = new StreamReader(data))
{
_responestring = reader.ReadToEnd();
}
}
catch (WebException)
{
}
}
I would suggest you to use RestSharp for your POST requests in windows phone. I am making an app for a startup and i faced lots of problems while using a similar code as yours. heres an example of a post request using RestSharp. You see, instead of using 3 functions it can be done in a more concise form. Also the response can be handled efficiently. You can get RestSharp from Nuget.
RestRequest request = new RestRequest("your url", Method.POST);
request.AddParameter("key", value);
RestClient restClient = new RestClient();
restClient.ExecuteAsync(request, (response) =>
{
if (response.StatusCode == HttpStatusCode.OK)
{
StoryBoard2.Begin();
string result = response.Content;
if (result.Equals("success"))
message.Text = "Review submitted successfully!";
else
message.Text = "Review could not be submitted.";
indicator.IsRunning = false;
}
else
{
StoryBoard2.Begin();
message.Text = "Review could not be submitted.";
}
});
It turned out the problem was on the server-side: it tried it on the server of a friend and it worked fine, there. I'll contact the support of the hoster and provide details as soon as I get a response.