I need to get the 500 error response message from HttpWebResponse.
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
using (StreamReader responseStream = new StreamReader(objResponse.GetResponseStream()))
{
post_response = responseStream.ReadToEnd();
responseStream.Close();
}
Thank you!
[EDIT]
open this url using browser,
https://www.sagepayments.net/web_services/vterm_extensions/transaction_processing.asmx/BANKCARD_PRIOR_AUTH_SALE
The browser will print response message, 'Missing parameter: M_ID."
Now, I want to get that response message using asp.net
var post_string = "hello=hi";
HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create("https://www.sagepayments.net/web_services/vterm_extensions/transaction_processing.asmx/BANKCARD_PRIOR_AUTH_SALE");
objRequest.Method = "POST";
objRequest.ContentLength = post_string.Length;
objRequest.ContentType = "application/x-www-form-urlencoded";
// post data is sent as a stream
StreamWriter myWriter = null;
myWriter = new StreamWriter(objRequest.GetRequestStream());
myWriter.Write(post_string);
myWriter.Close();
// returned values are returned as a stream, then read into a string
try
{
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
using (StreamReader responseStream = new StreamReader(objResponse.GetResponseStream()))
{
post_response = responseStream.ReadToEnd();
responseStream.Close();
}
Response.Write(post_response);
}
catch(WebException e)
{
Response.Write("Error : "+e.Message);
Response.Write("<br /> Data : " + e.Data);
Response.Write("<br /> HelpLink : " + e.HelpLink);
Response.Write("<br /> InnerException : " + e.InnerException);
Response.Write("<br /> Response : " + e.Response);
Response.Write("<br /> Source : " + e.Source);
Response.Write("<br /> Status : " + e.Status);
Response.Write("<br /> TargetSite : " + e.TargetSite);
}
Result :
Error : The remote server returned an error: (500) Internal Server Error.
Data : System.Collections.ListDictionaryInternal
HelpLink :
InnerException :
Response : System.Net.HttpWebResponse
Source : System
Status : ProtocolError
TargetSite : System.Net.WebResponse GetResponse()
How to get this message ?
Missing parameter: M_ID.
I think you need to check the StatusCode & StatusDescription properties of the web response if an exception is thrown during the web request.
For example:
try
{
HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
using (StreamReader responseStream = new StreamReader(objResponse.GetResponseStream()))
{
post_response = responseStream.ReadToEnd();
responseStream.Close();
}
}
catch(WebException wex)
{
// This is the line that gets you the response object
HttpWebResponse response = (HttpWebResponse)wex.Response;
if(response != null)
{
// You can now read the response StatusCode and StatusDescription
HttpStatusCode responseCode = response.StatusCode;
String statusDescription = response.StatusDescription;
// Add your status checking logic here
}
}
HTTP Errors are handled at the IIS level unless you have custom errors turned on. Check out this post on how to change your web config to add your own custom error pages: Returning 404 Error ASP.NET MVC 3
This question:
How to send a Status Code 500 in ASP.Net and still write to the response?
...also features specifically how a 500 might be thrown and again how to do customer errors. It also includes a bit on Context.Response.TrySkipIisCustomErrors which is the accepted answer.
That's work in my situation. Hope it wold help you.
try
{
response = (HttpWebResponse)request.GetResponse();
using (StreamReader streamReader = new StreamReader(response.GetResponseStream()))
{
responseMessage = streamReader.ReadToEnd();
Assert.IsTrue(response.StatusCode == HttpStatusCode.OK);
response.Close();
}
}
catch(WebException ex)
{
using (StreamReader streamReader = new StreamReader(ex.Response.GetResponseStream()))
{
responseMessage = streamReader.ReadToEnd();
File.WriteAllText(#"C:\Users\Paul\Documents\text.txt", responseMessage);
}
}
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();
}
}
}
the catch is supposed to give me a 504 but for someone reason, I get a null on:
response = (HttpWebResponse)e.Response;
Below is my code:
var url = "http://www.go435345ogle.com";
HttpWebResponse response = null;
HttpStatusCode statusCode;
get http response
get status
try
{
// Creates an HttpWebRequest for the specified URL.
HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
//HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(keys.Value.Substring(0, keys.Key.Length - 1));
// Sends the HttpWebRequest and waits for a response.
response = (HttpWebResponse)myHttpWebRequest.GetResponse();
}
catch (WebException e)
{
Console.WriteLine("\r\nWebException Raised. The following error occured : {0}", e.Status);
response = (HttpWebResponse)e.Response;
}
statusCode = response.StatusCode;
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
var sResponse = reader.ReadToEnd();
// Console.WriteLine(sResponse);
Console.WriteLine("Response Code: " + (int)statusCode + " - " + statusCode.ToString());
}
This is expected behaviour. Since domain www.go435345ogle.com doesn't exist, there is no server you could send request to, and therefore no response to receive. So WebException.Response simply returns null. Microsoft's docs clearly states, that WebException.Response returns:
If a response is available from the Internet resource, a WebResponse
instance that contains the error response from an Internet resource;
otherwise, null.
I made an API in server side with PHP + Laravel framework which accept both GET & Post requests with some special parameters.
It's address is : http://beresun.ir/API/Orders/0
and it gets these parameters :
token > string ,
restaurant_id > integer ,
admin_id > integer ,
token_id > integer .
if we send a request with GET method with these parameters, for example it will be :
http://beresun.ir/API/Orders/0?token=2JEuksuv86DcFmLrQa7nna4QDeowuGTqpyUK0pf9wSlbe6D5hLtEVxvzMT5gAZG0xBKy00HxS3J79mcr8F54dBD0uIg5HX5fzPOAP&restaurant_id=1&admin_id=2&token_id=40 which returns a json data , you can click on the link to see the results .
the response json data includes some information about customers and it's products.
now I want to make a windows application for this service with C# and request data from this API with POST or GET methods :
I want to use this API to get Json data from Web server and save them in my Windows application , So I created two functions in one of my Form Classes :
using Newtonsoft.Json;
using System;
using System.IO;
using System.Net;
using System.Text;
using System.Windows.Forms;
public partial class MainActivity : Form
{
string token = "2JEuksuv86DcFmLrQa7nna4QDeowuGTqpyUK0pf9wSlbe6D5hLtEVxvzMT5gAZG0xBKy00HxS3J79mcr8F54dBD0uIg5HX5fzPOAP";
int restaurant_id = 1;
int admin_id = 2;
int token_id = 40;
private void SendWebrequest_Get_Method()
{
try
{
String postData = "token=" + token +
"&restaurant_id=" + restaurant_id +
"&admin_id=" + admin_id +
"&token_id=" + token_id;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://beresun.ir/API/Orders/0?" + postData);
request.ContentType = "application/json; charset=utf-8";
request.Accept = "application/json";
request.Method = WebRequestMethods.Http.Get;
WebResponse response = request.GetResponse();
StreamReader sr = new StreamReader(response.GetResponseStream());
String json_text = sr.ReadToEnd();
dynamic stuff = JsonConvert.DeserializeObject(json_text);
if (stuff.error != null)
{
MessageBox.Show("problem with getting data", "Error");
}
else
{
MessageBox.Show(json_text, "success");
}
sr.Close();
}
catch (Exception ex)
{
MessageBox.Show("Wrong request ! " + ex.Message, "Error");
}
}
private void SendWebrequest_POST_Method()
{
try
{
// Create a request using a URL that can receive a post.
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://beresun.ir/API/Orders/5");
// Set the Method property of the request to POST.
request.Method = "POST";
request.Credentials = CredentialCache.DefaultCredentials;
((HttpWebRequest)request).UserAgent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";
// Create POST data and convert it to a byte array.
string postData = "token=" + token +
"&restaurant_id=" + restaurant_id +
"&admin_id=" + admin_id +
"&token_id=" + token_id;
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Set the ContentType property of the WebRequest.
request.ContentType = "application/json; charset=utf-8";
// Set the ContentLength property of the WebRequest.
request.ContentLength = byteArray.Length;
// Get the request stream.
Stream dataStream = request.GetRequestStream();
// Write the data to the request stream.
dataStream.Write(byteArray, 0, byteArray.Length);
// Close the Stream object.
dataStream.Close();
// Get the response.
WebResponse response = request.GetResponse();
// Display the status.
MessageBox.Show(((HttpWebResponse)response).StatusDescription);
// Get the stream containing content returned by the server.
dataStream = response.GetResponseStream();
// Open the stream using a StreamReader for easy access.
StreamReader reader = new StreamReader(dataStream);
// Read the content.
string responseFromServer = reader.ReadToEnd();
// Display the content.
MessageBox.Show(responseFromServer);
// Clean up the streams.
reader.Close();
dataStream.Close();
response.Close();
}
catch (Exception ex)
{
MessageBox.Show("Wrong request ! " + ex.Message, "Error");
}
}
}
Now Here is the problem , when I test the API it works fine , but when I request data from my application , it returns error and not working .
Can anyone explain me how I should request data from this API , to get data , I searched a lot , and I used many different methods , but none of them worked for me . maybe because this API returns very much Json data or maybe request timeout happen. I don't know , I couldn't find the problem . So I asked it Here.
I don't know what I should do .
Thanks
Oki so i run your code :
private string TestURL = "http://beresun.ir/API/";
string token = "2JEuksuv86DcFmLrQa7nna4QDeowuGTqpyUK0pf9wSlbe6D5hLtEVxvzMT5gAZG0xBKy00HxS3J79mcr8F54dBD0uIg5HX5fzPOAP";
int restaurant_id = 1;
int admin_id = 2;
int token_id = 40;
public async Task<string> test()
{
try
{
using (var Client = new HttpClient())
{
Client.BaseAddress = new Uri(TestURL);
Client.DefaultRequestHeaders.Accept.Clear();
Client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
string postData = "token=" + token +
"&restaurant_id=" + restaurant_id +
"&admin_id=" + admin_id +
"&token_id=" + token_id;
HttpResponseMessage responce = await Client.GetAsync("Orders/0?" + postData);
if (responce.IsSuccessStatusCode)
{
var Json = await responce.Content.ReadAsStringAsync();
// !
return Json;
}
else
{
// deal with error or here ...
return null;
}
}
}
catch (Exception e)
{
return null;
}
}
and its working am getting the json file ,, i think your mistake is in postData is string Not String ! a simple type can amazing harm !
try this:
private string URL = "Your Base domain URL";
public async Task<YourModel> getRequest()
{
using (var Client = new HttpClient())
{
Client.BaseAddress = new Uri(URL);
Client.DefaultRequestHeaders.Accept.Clear();
Client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage responce = await Client.GetAsync("Your Method or the API you callig");
if (responce.IsSuccessStatusCode)
{
var Json = await responce.Content.ReadAsStringAsync();
var Items= JsonConvert.DeserializeObject<YourModel>(Json);
// now use you have the date on Items !
return Items;
}
else
{
// deal with error or here ...
return null;
}
}
}
I'm trying to call http://genderize.io/ , but i'm getting an error from .NET saying:
{"You must provide a request body if you set ContentLength>0 or SendChunked==true. Do this by calling [Begin]GetRequestStream before [Begin]GetResponse."}
How would I call this web service "http://api.genderize.io/?name=peter" from C# and get a JSON string back?
HttpWebRequest request;
string postData = "name=peter"
URL = "http://api.genderize.io/?"
Uri uri = new Uri(URL + postData);
request = (HttpWebRequest)WebRequest.Create(uri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = postData.Length;
request.AllowAutoRedirect = true;
UTF8Encoding enc = new UTF8Encoding();
string result = string.Empty;
HttpWebResponse Response;
try
{
using (Response = (HttpWebResponse)request.GetResponse())
{
using (Stream responseStream = Response.GetResponseStream())
{
using (StreamReader readStream = new StreamReader(responseStream, Encoding.UTF8))
{
return readStream.ReadToEnd();
}
}
}
}
catch (Exception ex)
{
Debug.WriteLine("Error: " + ex.Message);
throw ex;
}
You are making the call to the service using POST method, reading through the comments area in http://genderize.io/ the author states that only GET method requests are allowed.
Stroemgren: Yes, this is confirmed. Only HTTP GET request are allowed.
This answer probably would be better as a comment, but I don't have enough reputation :(
Here is code I use to POST into RESTful web service. My problem is with a last line.
For example, my server can reply with different messages and same code.
Now, unless I get 200 OK I just get exception on last line.
I'd like to have better access to response header, etc no matter what code I got. How is that possible?
var request = WebRequest.Create(Options.DitatServerUri + Options.DitatAccountId + "/integration/trip") as HttpWebRequest;
if (request == null) return false;
request.ContentType = "application/json";
request.Headers.Add(HttpRequestHeader.Authorization, "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(Options.DitatLoginName + ":" + Options.DitatPassword)));
request.Method = "POST";
var serializer = new JavaScriptSerializer();
var serializedData = serializer.Serialize(trip);
var bytes = Encoding.UTF8.GetBytes(serializedData);
request.ContentLength = bytes.Length;
var os = request.GetRequestStream();
os.Write(bytes, 0, bytes.Length);
os.Close();
var response = request.GetResponse();
Example: I get WebException "Invalid Operation" but server actually send message with error explanation.
Building on what Jon said above in the comments, the exception thrown for a bad status code is most likely a WebException, which has Response and Status properties, as per this MSDN page. Therefore, you can get the response via:
WebResponse response = null;
try
{
response = request.GetResponse();
}
catch (WebException ex)
{
response = ex.Response;
}
Why not catch the exception and handle it appropriately?
try
{
var response = request.GetResponse();
}
catch (WebException webEx)
{
Console.WriteLine("Error: {0}", ((HttpWebResponse)webEx.Response).StatusDescription);
}