添加页眉和邮政数据在C#中REST风格/ HTTP请求 [英] Adding Headers and Post data in RESTfull/HTTP Request in C#

查看:159
本文介绍了添加页眉和邮政数据在C#中REST风格/ HTTP请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有问题,发送POST请求在C#中,似乎我误解了一些HTTP基础知识。所以基本上我实现REST风格的服务的客户端,它的工作如下:

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. 请POST请求,用户名/密码,获得令牌
  2. 在头部使用此令牌(授权:TOKEN),同时使其他GET / POST / PUT请求

我用的WebRequest 来使GET请求(与Authorization头)和它的工作。但是当我使用下面的code键使PUT请求,服务是给验证失败 - 没有登陆的消息:

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

我必须做一些小的错误(至少我希望如此),同时发送POST请求。所以我在做什么错了?

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

感谢。

推荐答案

动头的要求蒸汽工程前(按AI W酒店的评论),因为请求流增加身体。

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

该方法被WebRequest的内部实现,你需要写正文之前完成头部,一旦它在流格式,它准备发送。

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.

如果你看一下在WebRequest的反射器或一些这样的反编译工具的实施,你就可以看到的逻辑。

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

希望这有助于

这篇关于添加页眉和邮政数据在C#中REST风格/ HTTP请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆