简体   繁体   English

如何使用C#HttpWebRequest发布原始数据

[英]How to POST Raw Data using C# HttpWebRequest

I am trying to make a POST request in which I am supposed to send Raw POST data. 我正在尝试发出一个POST请求,我应该发送Raw POST数据。

Which property should I modify to achieve this. 我应该修改哪个属性来实现此目的。

Is it the HttpWebRequest.ContentType property. 它是HttpWebRequest.ContentType属性。 If, so what value should I assign to it. 如果,那么我应该赋予它什么价值。

public static string HttpPOST(string url, string querystring)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
    request.ContentType = "application/x-www-form-urlencoded"; // or whatever - application/json, etc, etc
    StreamWriter requestWriter = new StreamWriter(request.GetRequestStream());

    try
    {
        requestWriter.Write(querystring);
    }
    catch
    {
        throw;
    }
    finally
    {
        requestWriter.Close();
        requestWriter = null;
    }

    HttpWebResponse response = (HttpWebResponse)request.GetResponse();
    using (StreamReader sr = new StreamReader(response.GetResponseStream()))
    {
        return sr.ReadToEnd();
    }
}

You want to set the ContentType property to the mime type of the data. 您希望将ContentType属性设置为数据的mime类型。 If its a file, it depends on the type of file, if it's plain text then text/plain and if it's an arbitrary binary data of your own local purposes then application/octet-stream. 如果它是一个文件,它取决于文件的类型,如果它是纯文本然后是text / plain,如果它是你自己的本地目的的任意二进制数据那么application / octet-stream。 In the case of text-based formats you'll want to include the charset along with the content type, eg "text/plain; charset=UTF-8". 对于基于文本的格式,您需要将charset与内容类型一起包括在内,例如“text / plain; charset = UTF-8”。

You'll then want to call GetRequestStream() and write the data to the stream returned. 然后,您需要调用GetRequestStream()并将数据写入返回的流。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM