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

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());
}
}
}

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");

HTTPWebResponse "GET" API Call Exception - C#

I'm attempting to access a remote API and I'm getting a few exceptions during the HTTPWebResponse call. Below is my code:
//url
string responseValue = string.Empty;
HttpWebRequest request = (HttpWebRequest)WebRequest.Create("www.someapi.com")
request.Method = "GET";
request.UseDefaultCredentials = true;
request.ContentType = "application/json; charset=utf-8";
request.Headers("x-ms-client-id", "data");
try{
using (var response = (HttpWebRequest)req.GetResponse()){ <--- this line is the one that fails. System.IO.IOException here.
using (var stream = response.GetResponseStream()){
using(var sr = new StreamReader(stream)){
responseValue = sr.ReadToEnd();
}
}
}
} catch ///catch
The errors I'm getting are SocketExceptions and WebExceptions. I'm not sure why this specific call is failing. When I attempt the same URL and headers in Postman, the call returns a 200.
Any ideas would be appreciated.
EDIT:
Adding the error messages I'm getting. The exception being thrown when the response is attempted is
System.IO.IOException: "Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host."
Usually, I often use HttpWebRequest like below code.
You can download the HttpHelper I compiled and call it according to my reference example, or you can add Http Header as required.
How to invoke HttpHelper, ex: Get Method
Console app to use azure storage tableapi
String PostParam = String.Empty;
if (Data != null)
{
PostParam = Data.ToString();//Newtonsoft.Json.JsonConvert.SerializeObject(Data);
}
byte[] postData = Encoding.UTF8.GetBytes(PostParam);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri(url + (Id == null ? "" : '/' + Id.ToString())));
request.Method = Method;
request.ServicePoint.Expect100Continue = false;
request.Timeout = HttpRequestTimeOut;
request.ContentType = "application/json";
request.ContentLength = postData.Length;
if (postData.Length > 0)
{
using (Stream requestStream = request.GetRequestStream())
{
requestStream.Write(postData, 0, postData.Length);
}
}
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
Response.Code = response.StatusCode;
using (StreamReader stream = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
{
Response.Data = stream.ReadToEnd();
}
}

Why does my API POST Request keep failing?

I am doing an API Post request and cant seem to get it to work. I always get a sendFailure webexception and the response for the exception is always null so catching the exception is useless. It keeps happening when I try to get the httpWebResponse. I noticed too the request.contentlength gave errors at postream getrequeststream so i commented it out. Test.json is the file I use for the request body. I also tested this on different API testers by including the URL, body, and content-type in the header and they worked. I just cant seem to code it for myself. The credentials work I just dont know if im doing the request correctly?
JSON File:
{
"email": "abc#123.com",
"password": "12345",
"facilityNumber": "987654"
}
string filepath = "test.json";
string result = string.Empty;
using (StreamReader r = new StreamReader(filepath))
{
var json = r.ReadToEnd();
var jobj = JObject.Parse(json);
foreach (var item in jobj.Properties())
{
item.Value = item.Value.ToString().Replace("v1", "v2");
}
result = jobj.ToString();
Console.WriteLine(result);
}
try
{
string setupParameters;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("https://www.test.com/abcde");
request.AllowAutoRedirect = true;
setupParameters = result;
ServicePointManager.ServerCertificateValidationCallback = (s, cert, chain, ssl) => true;
ASCIIEncoding encoding = new ASCIIEncoding();
var postData = setupParameters;
request.Method = "POST";
request.ContentType = "application/json";
byte[] data = encoding.GetBytes(postData);
//request.ContentLength = data.Length;
using (StreamWriter postStream = new StreamWriter(request.GetRequestStream()))//error if uncomment contentlength
{
postStream.Write(postData);
postStream.Flush();
postStream.Close();
}
HttpWebResponse wr = (HttpWebResponse)request.GetResponse();//error occurs
Stream receiveStream = wr.GetResponseStream();
StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);
}
catch (WebException ex)
{
if (ex.Response != null)
{
using (var errorResponse = (HttpWebResponse)ex.Response)
{
using (var reader = new StreamReader(errorResponse.GetResponseStream()))
{
string error = reader.ReadToEnd();
result = error;
}
}
}
I suggest modifiying your request to follow this format. Especially pay attention to the request.Method and request.ContentType which have caught me out multiple times.
Also, handling the response is easier this way.
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(YOURURL);
request.ContentType = "application/json; charset=utf8";
request.Headers.Add(ADD HEADER HERE IF YOU NEED ONE);
request.Method = WebRequestMethods.Http.Post; // IMPORTANT
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(JsonConvert.SerializeObject(JSONBODYSTRING));
// I USUALLY YOU JSONCONVERT HERE TO SIMPLY SERIALIZE A STRING CONTAINING THE JSON INFO.
//BUT I GUESS YOUR METHOD WOULD ALSO WORK
streamWriter.Flush();
streamWriter.Close();
}
WebResponse response = request.GetResponse();
using (var streamReader = new StreamReader(response.GetResponseStream()))
{
string result = streamReader.ReadToEnd();
// DO WHATEVER YOU'D LIKE HERE
}
} catch (Exception ex)
{
// HANDLE YOUR EXCEPTIONS
}

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

Parsing POST request data with FiddlerCore

I'm tring to capture a local POST requset and parse its data.
For testing only, the FiddlerCore should only response with the data it has parsed.
Here's the code of the FidlerCore encapsulation:
private void FiddlerApplication_BeforeRequest(Session oSession)
{
if (oSession.hostname != "localhost") return;
eventLog.WriteEntry("Handling local request...");
oSession.bBufferResponse = true;
oSession.utilCreateResponseAndBypassServer();
oSession.oResponse.headers.HTTPResponseStatus = "200 Ok";
oSession.oResponse["Content-Type"] = "text/html; charset=UTF-8";
oSession.oResponse["Cache-Control"] = "private, max-age=0";
string body = oSession.GetRequestBodyAsString();
oSession.utilSetResponseBody(body);
}
Here's the code of the request sender:
const string postData = "This is a test that posts this string to a Web server.";
try
{
WebRequest request = WebRequest.Create("http://localhost/?action=print");
byte[] byteArray = Encoding.UTF8.GetBytes(postData);
request.ContentLength = byteArray.Length;
request.ContentType = "text/html";
request.Method = "POST";
using (Stream stream = request.GetRequestStream())
{
stream.Write(byteArray, 0, byteArray.Length);
}
using (WebResponse response = request.GetResponse())
{
txtResponse.Text = ((HttpWebResponse)response).StatusDescription;
using (Stream stream = response.GetResponseStream())
{
using (StreamReader streamReader = new StreamReader(stream))
{
string responseFromServer = streamReader.ReadToEnd();
streamReader.Close();
txtResponse.Text = responseFromServer;
}
}
}
}
catch (Exception ex)
{
txtResponse.Text = ex.Message;
}
I'm getting the following error:
The server committed a protocol violation. Section=ResponseStatusLine
What am I doing wrong?
Got it to work by changing:
WebRequest request = WebRequest.Create("http://localhost/?action=print");
to
WebRequest request = WebRequest.Create("http://localhost:8877/?action=print");
Calling this URL from a browser is intercepted by FiddlerCore correctly, without having to specify the port number. I did not think I should have inserted the listening port, since FiddlerCore should intercept all traffic, right?

Categories

Resources