C# - Receiving strange character from HttpWebResponse - c#

I have this code to send a HTTP Request:
public string MakeRequest(string requestUrl, object data)
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(requestUrl);
request.ContentType = "application/json";
request.KeepAlive = false;
request.Headers.Add("Authorization", "BEARER " + apiToken);
System.Net.ServicePointManager.Expect100Continue = false;
if (data != null)
{
request.Method = "POST";
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
string json = new JavaScriptSerializer().Serialize(data);
streamWriter.Write(json);
streamWriter.Flush();
streamWriter.Close();
}
}
else
request.Method = "GET";
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK && response.StatusCode != HttpStatusCode.Created)
throw new Exception(String.Format("Server error (HTTP {0}: {1}).", response.StatusCode, response.StatusDescription));
string Charset = response.CharacterSet;
Encoding encoding = Encoding.GetEncoding(Charset);
StreamReader reader = new StreamReader(response.GetResponseStream(), encoding);
return reader.ReadToEnd();
}
}
It works well for most calls but one POST where I receive this as response:
"�\b\0\0\0\0\0\0�V�M,.I-�/JI-R��V3<S����L�L,�L��jk[���&\0\0\0"
And when I see the call captured by Fiddler it says the routine received:
{
"MasterOrder": {
"OrderId": "65250824"
}
}
So, what is happening exactly? How is that Fiddler sees one response and the applications sees another response?

Solved the issue by adding these lines to the request:
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

Related

Getting 400 (bad request) when trying to send a message to slack with webhook URL

I'm trying to send a message to a slack channel in C#. with http request, using Webhook url.
In the get response line' I'm getting 400- bad request.
My function:
public void SendSlackAlert(string message, string slackUrl)
{
try
{
var content = $"{{\r\n\"text\":\"{Context}\r\n{message} \"\r\n}}";
if (string.IsNullOrWhiteSpace(slackUrl))
{
return;
}
var httpRequest = WebRequest.Create(slackUrl) as HttpWebRequest;
httpRequest.Method = "POST";
httpRequest.Accept = "application/json";
httpRequest.Timeout = Convert.ToInt32(TimeSpan.FromDays(1).TotalMilliseconds);
var bytesToSend = Encoding.UTF8.GetBytes(content);
httpRequest.ContentType = "application/json;charset=utf-8";
httpRequest.ContentLength = bytesToSend.Length;
using (var requestStream = httpRequest.GetRequestStream())
requestStream.Write(bytesToSend, 0, bytesToSend.Length);
var httpResponse = httpRequest.GetResponse() as HttpWebResponse;
using (var responseReader = new StreamReader(httpResponse.GetResponseStream(), Encoding.UTF8))
{
responseReader.ReadToEnd();
}
}
catch (Exception ex)
{
// return "Error";
}
}
I am transferred to catch with the error, in this line:
var httpResponse = httpRequest.GetResponse() as HttpWebResponse;
would greatly appreciate any attempt to help.
Thank you!
I saw elsewhere that having the encoding set can cause issues with the Slack API.
Instead of setting the Content-Type header along with an encoding, try only setting the Content-Type header to application JSON.
Replace this line:
httpRequest.ContentType = "application/json;charset=utf-8";
With this line:
httpRequest.Headers.Add(HttpRequestHeader.ContentType, "application/json");

HttpWebRequest - payload error

HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(url);
Request.Headers.Add("Authorization", "OAuth " + GetAccessTokenBeta());
Request.Proxy.Credentials = CredentialCache.DefaultCredentials;
Request.Method = "POST";
Request.ContentType = "application/xml";
using (var streamWriter = new StreamWriter(Request.GetRequestStream()))
{
string xml = getXml(tabletype, values.ToArray());
streamWriter.Write(xml);
streamWriter.Flush();
streamWriter.Close();
}
try
{
using (WebResponse response = Request.GetResponse())
{
using (StreamReader rd = new StreamReader(response.GetResponseStream()))
{
}
}
}
catch (WebException ex)
{
var resp = new StreamReader(ex.Response.GetResponseStream()).ReadToEnd();
Core.ShowError("Error connecting to the webservice." + "\r\n" + resp);
}
I have confirmed that the endpoint and XML work using Postman, but I am running into this issue in C#.
Error sending HTTP request. Message payload is of type: BufferInputStream

Getting exception Newtonsoft.Json.JsonReaderException

I request for gZip response in Header like :
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip");
In webresponse I am getting ContentEncoding = gzip
I don't know how to decompress gzip response with my code and when I read the string with json I getting Newtonsoft.Json.JsonReaderException
What is the solution ?
using (WebResponse response = GetWebResponse(request))
using (StreamReader reader = new StreamReader(response.GetResponseStream()))
{
var result = reader.ReadToEnd();
return JsonConvert.DeserializeObject<T>(result);
}
This is how I construct request :
var request = CreateWebRequest(new Uri(uri), type);
// create request stream from arguments
if (args != null)
{
string requestData = string.Empty;
requestData = Newtonsoft.Json.JsonConvert.SerializeObject(args, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore });
var data = Encoding.GetEncoding("UTF-8").GetBytes(requestData);
request.ContentLength = data.Length;
using (Stream stream = request.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
}
protected WebRequest CreateWebRequest(Uri uri, MethodType type, bool IsUrlEncoded = false)
{
WebRequest request = WebRequest.Create(uri);
(request as HttpWebRequest).Accept = "application/json";
System.Net.ServicePointManager.Expect100Continue = false;
if (IsUrlEncoded)
request.ContentType = "application/x-www-form-urlencoded";
else
request.ContentType = "application / json";
request.Headers.Add("X-Application", AppKeyData.Appkey);
if (!string.IsNullOrEmpty(AppKeyData.SessionToken))
{
request.Headers.Add("X-Authentication", AppKeyData.SessionToken);
}
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip");
request.Method = type.ToString();
return request;
}
You have to set AutomaticDecompression property on your request.
request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;
Update:
You can include below line in your CreateWebRequest method.
(request as HttpWebRequest).AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

Json POST request to the server but server respond (400) Bad Request

I want to use google api for creation of gmail user account. I am sending JSON request to server for getting authorization code but I got these error in httpwebresponse :-
Exception Details: System.Net.WebException: The remote server returned an error: (400) Bad Request
var request = (HttpWebRequest)WebRequest.Create(#"https://accounts.google.com/o/oauth2/auth");
request.Method = "POST";
request.ContentType = "text/json";
request.KeepAlive = false;
//request.ContentLength = 0;
using (StreamWriter streamWriter = new StreamWriter(request.GetRequestStream()))
{
string json = "{\"scope\":\"https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile\"," + "\"state\":\"%2Fprofile\"," + "\"redirect_uri\":\"http://gmailcheck.com/response.aspx\"," + "\"response_type\":\"code\"," + "\"client_id\":\"841994137170.apps.googleusercontent.com\"}";
streamWriter.Write(json);
// streamWriter.Flush();
//streamWriter.Close();
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
StreamReader responsereader = new StreamReader(response.GetResponseStream());
var responsedata = responsereader.ReadToEnd();
//Session["responseinfo"] = responsereader;
//testdiv.InnerHtml = responsedata;
}
}
As soon as you get an exception, you have to read the actual responce from server there should be something helpfull. Like an error description or extended status code...
For Instance:
try
{
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
... your code goes here....
}
catch (WebException ex)
{
using (WebResponse response = ex.Response)
{
var httpResponse = (HttpWebResponse)response;
using (Stream data = response.GetResponseStream())
{
StreamReader sr = new StreamReader(data);
throw new Exception(sr.ReadToEnd());
}
}
}

How to get value back from a web services in C#?

I am sending a URL and XML to a webservices, so that it will return me JSON about the result. I am here posting the request to the webservices how do I get the value from the webservices back. The value returned by the webservices is JSON. What should be the return type here and what should be returned to get the HTTP response status and body
public string HttpPostcredentials(string XML, string url)
{
try
{
HttpWebRequest req = WebRequest.Create(new Uri(url)) as HttpWebRequest;
req.Method = "POST";
byte[] buffer = Encoding.ASCII.GetBytes(XML);
req.ContentLength = buffer.Length;
req.ContentType = "application/xml";
Stream PostData = req.GetRequestStream();
PostData.Write(buffer, 0, buffer.Length);
PostData.Close();
}
catch (Exception e)
{
}
return null;
}
Is this what you are looking for:
var request = WebRequest.Create(string.Concat(serviceUrl, resourceUrl)) as HttpWebRequest;
if (request != null)
{
request.ContentType = "application/xml";
request.Method = "POST";
}
byte[] requestBodyBytes = Encoding.ASCII.GetBytes(XML);
request.ContentLength = requestBodyBytes.Length;
using (Stream postStream = request.GetRequestStream())
postStream.Write(requestBodyBytes, 0, requestBodyBytes.Length);
if (request != null)
{
var response = request.GetResponse() as HttpWebResponse;
if(response.StatusCode == HttpStatusCode.OK)
{
Stream responseStream = response.GetResponseStream();
if (responseStream != null)
{
var reader = new StreamReader(responseStream);
responseMessage = reader.ReadToEnd();
}
}
else
{
responseMessage = response.StatusDescription;
}
}
You need to get the Response from the HttpWebRequest
WebResponse result = req.GetResponse();

Categories

Resources