HttpClient发布数据失败 [英] HttpClient Post Data Failed
问题描述
我正在创建一个Metro应用程序,它向Web服务器发出HTTP Post请求以获取XML数据, 最初
我使用相同的代码成功登录到Web服务器然后我发出多个Post Request来检索其他数据,但调用从未完成:
private async Task<string> PostData(string baseUrl, string data)
{
string ret = string.Empty;
HttpClientHandler handler = new HttpClientHandler();
handler.AllowAutoRedirect = false;
handler.UseDefaultCredentials = true;
handler.MaxRequestContentBufferSize = 20000;
var client = new HttpClient(handler);
//set RequestHeader (HTTP_USER_AGENT)
client.DefaultRequestHeaders.Add("user-agent",
"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
var httpRM = new HttpResponseMessage();
string useUrl = baseUrl;
if (Type == PostTypeEnum.Post)
{
var content = new StringContent(data);
try
{
httpRM = await client.PostAsync(useUrl, content);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
throw;
}
}
else if (Type == PostTypeEnum.Get)
{
client.DefaultRequestHeaders.Add("Content-Type",
"application/x-www-form-urlencoded");
if (data.Length > 0)
useUrl += "?" + data;
httpRM = await client.GetAsync(useUrl);
}
httpRM.EnsureSuccessStatusCode();
if (httpRM.IsSuccessStatusCode)
{
byte[] response = await httpRM.Content.ReadAsByteArrayAsync();
ret = new UTF8Encoding().GetString(response, 0, response.Length);
}
else
{
Debug.WriteLine("ATTENTION ! " + httpRM.StatusCode.ToString());
}
return ret;
}
推荐答案
嗨Amr,
如果没有完整的代码,这不是一个可以轻松调试的东西。 不过,我可以给你一些提示:
Without complete code this is not something that can easily be debugged. However, I can give you some tips:
1. 只创建一个HttpClient并在全局级别使用它。 不要每次都重新创建。
1. Only create one HttpClient and use it at a global level. Don't recreate each time.
2. 然后序列化您对HttpClient的调用,这样您就可以进行相同的连接(不要再进行另一次异步调用,直到前一次成功)。
2. Then serialize your calls to the HttpClient so you can you the same connection (don't make another async call until the previous succeeds).
3. system.net跟踪将帮助您了解正在发生的事情:
http://blogs.msdn.com/b/jpsanders/archive/2011/12/16/how-to-take-a-system-net-trace-from-metro- style-applications-developer-preview.aspx
3. A system.net trace will help you see what is going on: http://blogs.msdn.com/b/jpsanders/archive/2011/12/16/how-to-take-a-system-net-trace-from-metro-style-applications-developer-preview.aspx
-Jeff
这篇关于HttpClient发布数据失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!