[英]Is MonoTouch or the iOS web stack eating my HTTP DELETE request body?
[英]How can a pass a body with my POST and DELETE request using Http Web Request
我有一個通用方法 SendRequest,它在運行時發送請求以獲取 OAuth 令牌,然后也用於將我的請求發送到服務器。 我很少有 POST 和 DELETE 調用需要列表或字符串的主體。 但我不知道如何設置它。 我知道如何發送 Json 並對其進行序列化,但是當它只是一個字符串或列表類型時,我無法添加一個正文。
public HttpWebResponse SendRequest(string postData = "", Authentication.TokenType tokenType = Authentication.TokenType.Valid)
{
var messageBody = postData;
var strResponseValue = string.Empty;
var request = (HttpWebRequest)WebRequest.Create(EndPoint);
if (EndPoint == StringBuilderUtil.GenerateRequestURL("token"))
{
request.ContentType = "application/x-www-form-urlencoded";
request.Host = "identity-authority." +
ConfigurationManager.AppSettings["TestEnvironment"];
Token = ConfigurationManager.AppSettings["GenericSpecialCode"];
}
else
{
request.ContentType = "application/json";
Token = Authentication.ChooseToken(tokenType);
}
if (HttpMethod == HttpVerb.POST)
request.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip,deflate");
// Add some headers that are common to all calls.
request.KeepAlive = true;
request.Headers.Add("Authorization", AuthType.ToString() + " " + Token);
request.Method = HttpMethod.ToString();
request.Headers.Add("Cache-Control", "no-cache");
var lbPostBuffer = Encoding.Default.GetBytes(messageBody);
request.ContentLength = lbPostBuffer.Length;
if (HttpMethod == HttpVerb.POST)
{
var PostStream = request.GetRequestStream();
PostStream.Write(lbPostBuffer, 0, lbPostBuffer.Length);
PostStream.Close();
}
return request.GetResponse() as HttpWebResponse;
}
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/ec6hh.png
當它只是一個字符串或列表類型時如何添加一個正文。
如果您要發送一個字符串,除了編碼並將其放入 stream 之外,您不需要做太多事情。
列表類型與 object 的方式相同。 你必須先序列化它。
最后兩件事已經有邏輯了。
var lbPostBuffer = Encoding.Default.GetBytes(messageBody);
request.ContentLength = lbPostBuffer.Length;
if (HttpMethod == HttpVerb.POST)
{
var PostStream = request.GetRequestStream();
PostStream.Write(lbPostBuffer, 0, lbPostBuffer.Length);
PostStream.Close();
}
我假設序列化發生在調用SendRequest
方法之前,如果您使用的是 Newtonsoft.Json 它可以用JsonConvert.SerializeObject
完成
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.