Adding Headers and Post data in RESTfull/HTTP Requ

2019-03-14 16:50发布

问题:

I'm having problems with sending POST request in C# and it seems I misunderstood some HTTP basics. So basically I'm implementing RESTfull service client, which work as follows:

  1. Make POST request with username/password and get token
  2. Use this token in header (Authorization:TOKEN) while making other GET/POST/PUT requests

I use WebRequest to make GET requests (with Authorization header) and it's working. But when I use following code to make PUT requests, service is giving "Authentication failed - not logged in" message back:

String url = String.Format("{0}/{1}", AN_SERVER, app);
WebRequest theRequest = WebRequest.Create(url);
theRequest.Method = "POST";

theRequest.ContentType = "text/x-json";
theRequest.ContentLength = json.Length;
Stream requestStream = theRequest.GetRequestStream();

requestStream.Write(Encoding.ASCII.GetBytes(json), 0, json.Length);
requestStream.Close();


theRequest.Headers.Add("Authorization", authToken);

HttpWebResponse response =  (HttpWebResponse)theRequest.GetResponse();

I must be making minor mistake (at least I hope so) while sending POST request. So what am I doing wrong?

Thanks.

回答1:

Moving Headers before the request steam works (as per AI W's comment), because the request stream is adding the body.

The way webrequest is implemented internally, you need to finish the header before writing body, and once its in stream format, its ready to send.

If you look at the implementation of webrequest in reflector or some such decompiling tool, you'll be able to see the logic.

Hope this helps