开发者

Adding Headers and Post data in RESTfull/HTTP Request in C#

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 =  (HttpWe开发者_如何学编程bResponse)theRequest.GetResponse();

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

Thanks.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜