设置WebRequest的主体数据


120

我在ASP.NET中创建一个Web请求,并且需要向主体添加一堆数据。我怎么做?

var request = HttpWebRequest.Create(targetURL);
request.Method = "PUT";
response = (HttpWebResponse)request.GetResponse();

Answers:


105

HttpWebRequest.GetRequestStream

来自http://msdn.microsoft.com/zh-cn/library/d4cek6cc.aspx的代码示例

string postData = "firstone=" + inputData;
ASCIIEncoding encoding = new ASCIIEncoding ();
byte[] byte1 = encoding.GetBytes (postData);

// Set the content type of the data being posted.
myHttpWebRequest.ContentType = "application/x-www-form-urlencoded";

// Set the content length of the string being posted.
myHttpWebRequest.ContentLength = byte1.Length;

Stream newStream = myHttpWebRequest.GetRequestStream ();

newStream.Write (byte1, 0, byte1.Length);

从我自己的代码之一:

var request = (HttpWebRequest)WebRequest.Create(uri);
request.Credentials = this.credentials;
request.Method = method;
request.ContentType = "application/atom+xml;type=entry";
using (Stream requestStream = request.GetRequestStream())
using (var xmlWriter = XmlWriter.Create(requestStream, new XmlWriterSettings() { Indent = true, NewLineHandling = NewLineHandling.Entitize, }))
{
    cmisAtomEntry.WriteXml(xmlWriter);
}

try 
{    
    return (HttpWebResponse)request.GetResponse();  
}
catch (WebException wex)
{
    var httpResponse = wex.Response as HttpWebResponse;
    if (httpResponse != null)
    {
        throw new ApplicationException(string.Format(
            "Remote server call {0} {1} resulted in a http error {2} {3}.",
            method,
            uri,
            httpResponse.StatusCode,
            httpResponse.StatusDescription), wex);
    }
    else
    {
        throw new ApplicationException(string.Format(
            "Remote server call {0} {1} resulted in an error.",
            method,
            uri), wex);
    }
}
catch (Exception)
{
    throw;
}

嗨,Torbjorn,我正在使用请求,因此我可以获取“ request.GetResponse();”,在上面的示例中,它将如何工作?
William Calleja 2010年

当您调用GetRequestStream()时,它将调用服务器。因此,您必须将其添加到以上示例的末尾。
Torbjörn汉森

1
有没有一种方法可以查看请求对象中的全文以进行调试?我尝试对其进行序列化,并尝试使用StreamReader,但是无论如何我都看不到我刚刚写入请求的数据。
詹姆斯,

狂热的粉丝!

@James,您应该可以使用Fiddler或Wireshark查看其正文的完整请求。
RayLoveless

48

更新资料

看到我的其他答案。


原版的

var request = (HttpWebRequest)WebRequest.Create("https://example.com/endpoint");

string stringData = ""; // place body here
var data = Encoding.Default.GetBytes(stringData); // note: choose appropriate encoding

request.Method = "PUT";
request.ContentType = ""; // place MIME type here
request.ContentLength = data.Length;

var newStream = request.GetRequestStream(); // get a ref to the request body so it can be modified
newStream.Write(data, 0, data.Length);
newStream.Close();

你想念什么吗?就像httpWReq.Content = newStream; 您没有将newStream对象与webRequest一起使用。
Yogurtu'3

3
为了回答@Yogurtu的完整性问题StreamnewStream指向该对象的对象 直接写入请求的主体。可以通过调用来访问HttpWReq.GetRequestStream()。无需在请求上设置其他任何内容。
MojoFilter

0

这个主题的答案都很棒。但是我想提出另一个。很可能您已获得一个api,并希望将其纳入您的c#项目中。使用Postman,您可以在那里设置和测试api调用,一旦它正常运行,您只需单击“代码”,然后将您一直在处理的请求写入ac#片段。像这样:

var client = new RestClient("https://api.XXXXX.nl/oauth/token");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Basic   N2I1YTM4************************************jI0YzJhNDg=");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
request.AddParameter("grant_type", "password");
request.AddParameter("username", "development+XXXXXXXX-admin@XXXXXXX.XXXX");
request.AddParameter("password", "XXXXXXXXXXXXX");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);

上面的代码取决于nuget软件包RestSharp,您可以轻松安装该软件包。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.