400 Bad request exception when send JSON string to server from client - c#

Actually sending json string(Post) to server got 400 bad request exception,
below Url i got this exception
_http://---.---.--.---:---/SignUp/SignupUser/{JSON STRING}/{PASSWORD}
so the JSON string and password is given below
_http://---.---.--.---:----/SignUp/SignupUser/{"SessionId":"99c77c9b-043e-4611-a011-e774c614e887","PassWord":"234434343434","UserName":"john_mcclane","FirstName":"John","LastName":"mcclane","NickName":"Bruno","Gender":0,"DateTime":"2013-12-19T10:39:37","AddressLine1":"Paradigm Talent Agency NY","AddressLine2":"360 Park Ave South, 16th Floor","City":"New York","State":"New York","Country":"USA","Zip":"N.Y. 10010","EmailId":"Bruno_diehard#email.com","MobileNumber":"7189615565","AlternativeNumber":"9179615565","ProofType":"License","ProofNumber":"I1234562","IsDogAllowed":true,"IsDrinkersAllowed":true,"IsSmokersAllowed":true}/{234434343434}
please tell what i did wrong in it.
Note : I am trying this in the advance rest client google chrome.

You have created the POST request with two arguments (JSON object and password). The typical REST service post request can have only one argument. So, try with one argument by sending the password with the JSON object itself.

Related

Why is postman sending form data in an HTTP GET?

I received a Postman json collection from an API vendor that works perfectly, but has something mystifying to me: The request is in a GET format, yet there is an x-www-form-urlencoded body.
URL: https://login.microsoftonline.com/d1e<secret>9563/oauth2/token
And when I look at the postman-generated c# code, the mystery continues:
var client = new RestClient("https://login.microsoftonline.com/d1e...d3/oauth2/token");
client.Timeout = -1;
var request = new RestRequest(Method.GET);
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("grant_type", "client_credentials");
request.AddParameter("client_id", "c06bb...79");
request.AddParameter("client_secret", "7~u...D");
request.AddParameter("resource", "https://vault.azure.net");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
Note the AddParameter constructions for a GET call. To me, this must be a slight-of-hand for merely adding those values to the querystring. But when I look at the postman console I see:
In the postman console I would have expected to see those params appended to the url as a querystring, and then everything would have made sense. But you can see that it's a bonafide Request Body.
When I make GET calls in my c# code I like to use the simple yet solid WebClient object to call the DownloadString() method. But this method is only for GETs and there's no way to send a form-post style body, understandably.
Is postman truly sending a GET with all those values being appended to the url as a querystring? And should I do the same in my DownloadString() call? Or is there something else going on here? Should I instead, in my c#, be calling the UploadString() method and sending a form post BODY as a GET??
Http protocol supports adding a body to a request, but the WebClient class you use doesn't. Presumably because it isn't considered the norm.
I'm sure there's good reasons for Microsoft using it in the OAuth flow though. Those guys normally do things right!
HTTP GET with request body
API is just an abstraction , you can send what ever you want to the API . It depends on the implementation , how the server handles these data.
Some services considers only what it requires and ignores other information
some services considers the entire requests and validates that it has only the allowed data. what should be allowed depends on the service
Postman is just a client that sends data to server , its upto you to decide what all information it should send . If you dont need any body then keep it as none. if you need some thing then add it.

Gathering and Filtering Necessary Post Data for a HTTP Post Requests

I hope you're all well. I am trying to use C# and the request.post command to autofill a login page. I've shown the snippet of code I'm dealing with below.
My main concern currently is the 'POST DATA GOES HERE' .I'm unsure how I can gather the post-data as well as what syntax / format i would need to put it in.
I've already tried using Fiddler and Charles Proxy (HTTP Debuggers) to find anything about PostData . I did find some things I needed : User-Agent / Success Keys but those currently aren't relevant.
//Send a Post request to the (URL, postdata, contenttype) - store the HTTP Response into Response
var Response = Request.Post(LOGIN_URL, "{post data goes here}", "content type goes here `application/java`");

Processing Post Request from Slack

I've setup an asp.net MVC web application to capture post request. I've set breakpoints to see what info is coming through. When an interactive button is clicked, my breakpoint is hit but the object has no details. It simply says {Object} when i hover over value. When I use Postman and send a raw JSON body, it displays the JSON. May I ask how am i suppose to process the slack object that is sent?
public void Post(object value)
{
// breakpoint here
}
For interactive messages Slack send a standard POST request with a single form-data encoded parameter called payload in the body. This parameter contains the data of the actual request as JSON string.
You can simulate this with Postman by using the following parameters:
Request type: POST
Header: Content-Type: application/x-www-form-urlencoded
Body: form-data, with key=payload and value = JSON string.
So the body is not fully JSON as you assumed, but contains a form parameter with a JSON encoded string. If you change your app accordingly, it will work.
In c# you can access the content of the payload parameter with Request["payload"] (see this answer or details).
Then you still need to decode the JSON string into an object of course. An easy approach is to use JavaScriptSerializer.Deserialize. (see this answer for details and alternative approaches).

c# httpclient POST request: cant send special characters

I have a program that should login to site, it uses POST requests, and all goes fine, until one of the values contain special character('%' for example).
captcha = "ABCDE" //all goes fine and well, server accept captcha
captcha = "ABC&%" //server dont accept captcha and return fail
//here is the bad part:
string request = "password=" + HttpUtility.UrlEncode(encpass, Encoding.UTF8) +
"&username=" + login + "&captcha_text=" + HttpUtility.UrlEncode(captcha, Encoding.UTF8);
Also, i ofcourse googled it, and checked all i could find. I though i need to "warn" server abaut encoding, so i added
request.Headers.TryAddWithoutValidation("Content-Type", #"application/x-www-form-urlencoded; charset=UTF-8");
but it still did not helped me.
Content types and way request should look like i get from Firebug, so if i can find some answers there - please point.
modify0: Also, i compared what my program send to server with browser request(using Firebug) and my request is completley same. Only difference - my request dont get accepted in values it contain special-characters.
modify1: Also, server have no problems handling special-characters when i check it in browser. For example it(browser) sent "K&YF82" as "captcha_text=K%26YF82"(same value in addres propereties and request body) and all worked fine. UrlEncode do same replacement, but in my program it doesnt get accepted by server.
SOLUTION:
{ password:"df464dsj", username:"username", captchaText:"ABC&%", remember_login:"false" }
insteat of
password=f2341f14f&username=username&captha...
Are you dealing with REST application??
If yes then send your post data in request body instead of query string.
Also have a look at the stack post at : Special characters pose problems with REST webservice communication

C# HttpWebRequest.GetResponse - how is StatusCode usage handled for a non-exception vs webexception response?

Can someone help clear up the usage of the "StatusCode" property in HttpWebResponse and WebException?
For example it seems that if:
a) there is no exception, then the HttpWebResponse will have a StatusCode that could have some values that indicate both:
- success (e.g. OK, Accepted etc)
- failure (e.g. UseProxy, RequestTimeout etc)
b) there is a WebExeption throw, which itself has a response object that again has a StatusCode (which I assume is based on the same HttpStatusCode Enumeration.
Question 1
- Is there any consistency in terms of what StatusCode's will trigger a WebException (and you'd pick up the detail within the exception), versus which would come back without an exception but you'd find out the result in the StatusCode of the response object?
Question 2 - Or more specifically what is the pseduo code (or C# code itself) for trying to handle a httpWebRequest.GetResponse call such that you want to differentiate between the categories of responses for the user:
proxy settings / proxy issue
=> so can tell user to fix proxy settings
connectivity issue / web-server down
=> so user is aware of this
server side error (e.g. server is there but there is an issue handling the request - e.g content not there)
=> so user can raise with website manager
success case (and I assume this would be more than just the OK)
=> na (success case)
thanks
In my experience the response status code only returns 200 or 0. Anything else comes through the WebException, including proxy errors like 407 or 417.
The WebException is thrown whenever the web request cannot be executed successfully. For e.g 400 and 500 series of responses.
WebExcpetion has a property named Status which will return the actual status of the response i.e 500 (Internal Server Error).
Here is the list of all response codes: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
===============================================================================
In general:
1xx series of code = provisional response. These are not error codes. For e.g the 100 Continue response which tells that client should continue with its request. Usually WebRequest will not return such response, and handle it itself by sending the rest of request.
2xx series of code = Request was successful received, understood and accepted. These are not error codes. For e.g 200 OK
3xx series of code = Further action needs to be taken. Generally this is not error code (usually its for re-direction) for e.g '301 Moved Permanently', which means that the resource being request is moved to a new location, so any further requests by the client should be on the new URL provided in the response.
OR '305 Use Proxy', which according to you results in an Exception.
4xx series of code = Client errors. These can result in exception. for e.g '400 Bad Request' or '401 Unauthorized'
5xx series of code = Server errors. These can result in exception. for e.g '500 Internal Server Error' or '504 Gateway Timeout'

Categories