post取得 - webrequest c#




如何在C#中設置HttpWebRequest的內容? (4)

HttpWebRequest具有ContentLength和ContentType屬性,但是如何實際設置請求的內容?


.NET 4.5(或通過添加NuGet的Microsoft.Net.Http包提供.NET 4.0)在設置請求內容時提供了很多額外的靈活性。 這是一個例子:

private System.IO.Stream Upload(string actionUrl, string paramString, Stream paramFileStream, byte [] paramFileBytes)
{
    HttpContent stringContent = new StringContent(paramString);
    HttpContent fileStreamContent = new StreamContent(paramFileStream);
    HttpContent bytesContent = new ByteArrayContent(paramFileBytes);
    using (var client = new HttpClient())
    using (var formData = new MultipartFormDataContent())
    {
        formData.Add(stringContent, "param1", "param1");
        formData.Add(fileStreamContent, "file1", "file1");
        formData.Add(bytesContent, "file2", "file2");
        var response = client.PostAsync(actionUrl, formData).Result;
        if (!response.IsSuccessStatusCode)
        {
            return null;
        }
        return response.Content.ReadAsStreamAsync().Result;
    }
}

HttpWebRequest的RequestStream是動作所在的位置 - 粗略代碼......

//build the request object
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(http://someapi.com/);
//write the input data (aka post) to a byte array
byte[] requestBytes = new ASCIIEncoding().GetBytes(inputData);
//get the request stream to write the post to
Stream requestStream = request.GetRequestStream();
//write the post to the request stream
requestStream.Write(requestBytes, 0, requestBytes.Length);

如果您要發送擴展字符,請使用UTF8Encoding,請確保您也設置了正確的content-type / charset標頭。


以下內容應該讓您入門

byte[]  buffer = ...request data as bytes
var webReq = (HttpWebRequest) WebRequest.Create("http://127.0.0.1/target");

webReq.Method = "REQUIRED METHOD";
webReq.ContentType = "REQUIRED CONTENT TYPE";
webReq.ContentLength = buffer.Length;

var reqStream = webReq.GetRequestStream();
reqStream.Write(buffer, 0, buffer.Length);
reqStream.Close();

var webResp = (HttpWebResponse) webReq.GetResponse();

這裡有一個不同的選項,用於發布信息而不會弄亂Bytes和Streams。 我個人覺得更容易理解,閱讀和調試。

// Convert Object to JSON
var requestMessage = JsonConvert.SerializeObject(requestObject);
var content = new StringContent(requestMessage, Encoding.UTF8, "application/json");

// Create the Client
var client = new HttpClient();
client.DefaultRequestHeaders.Add(AuthKey, AuthValue);

// Post the JSON
var responseMessage = client.PostAsync(requestEndPoint, content).Result;
var stringResult = responseMessage.Content.ReadAsStringAsync().Result;

// Convert JSON back to the Object
var responseObject = JsonConvert.DeserializeObject<ResponseObject>(stringResult);




httpwebrequest