我正在创建一个使用C#和xamarin连接到我的网站api的android应用。经过一段时间的调试,我意识到当我设置ContentLength时,应用程序接缝会挂起,然后引发TIMEOUT异常。
我尝试不设置ContentLength,但是正文接缝不随请求一起发送。
public void Post(object data, string route){
string JSON = JsonConvert.SerializeObject(data);
var web = (HttpWebRequest)WebRequest.Create("http://httpbin.org/post");
//web.ContentLenfth = JSON.length;
web.ContentType = "application/json";
web.Method = "POST";
try{
var sw = new StreamWriter(webRequest.GetRequestStream());
sw.Write(JSON);
var webResponse = (HttpWebResponse)webRequest.GetResponse();
var sr = new StreamReader(webResponse.GetResponseStream());
var result = sr.ReadToEnd();
...
}
...
}
如果设置了ContentLengt,则应用程序将挂起,直到调用超时功能为止 否则我要发布的测试网址会告诉我我没有发送邮件
要发送成功的POST
请求,我该怎么做?
答案 0 :(得分:1)
您应该将长度设置为要发送的字节数组的长度(而不是字符串的长度)
您可以执行以下操作从json字符串中获取字节数组:
var bytes = Encoding.UTF8.GetBytes(JSON);
然后您可以设置内容长度:
web.ContentLength = bytes.length;
并发送字节:
using (var requestStream = web.GetRequestStream())
{
requestStream.Write(bytes, 0, bytes.Length);
}