为什么我用HTTPClient获取HttpRequestException? (C#)

时间:2014-09-30 15:29:48

标签: c# windows-phone httpclient httpresponse

我正在尝试创建一个自动连接某个Wi-Fi网络上用户的Windows Phone应用。 这个应用程序已经用Java编写,所以我要做的就是用C#“翻译”Java代码。

Java代码工作正常,这里是:

List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("referer", "https://captive.unisa.it/main.htm"));
formparams.add(new BasicNameValuePair("err_flag", "0"));
formparams.add(new BasicNameValuePair("username", user));
formparams.add(new BasicNameValuePair("password", pass));   
formparams.add(new BasicNameValuePair("buttonClicked", "4"));
formparams.add(new BasicNameValuePair("redirect_url", ""));

UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formparams, "UTF-8");
HttpPost httppost = new HttpPost(FORM_URL);
httppost.setEntity(entity);
HttpResponse response = mHttpClient.execute(httppost);
Log.v(Utils.TAG, "Post done...checking response");
String strRes = EntityUtils.toString(response.getEntity());

if (strRes.contains(LOGIN_SUCCESSFUL_PATTERN)) {
    // login successful
    return 1;
} else {
    return 3;
}

C#代码没有。我在 response.EnsureSuccessStatusCode();

上遇到异常
  

System.Net.HttpRequestException:“响应状态代码不表示成功:404(未找到)。”

以下是代码:

try
{
    var values = new List<KeyValuePair<string, string>>
    {
        new KeyValuePair<string, string>("referer", "https://captive.unisa.it/main.htm"),
        new KeyValuePair<string, string>("err_flag", "0"),
        new KeyValuePair<string, string>("username", USERNAME),
        new KeyValuePair<string, string>("password", PASSWORD),
        new KeyValuePair<string, string>("buttonClicked", "4"),
        new KeyValuePair<string, string>("redirect_url", "")
    };

    var httpClient = new HttpClient(new HttpClientHandler());       
    HttpResponseMessage response = await httpClient.PostAsync(FORM_URL, new FormUrlEncodedContent(values));              
    response.EnsureSuccessStatusCode();                       
    var responseString = await response.Content.ReadAsStringAsync();   

    if (responseString.Contains(LOGIN_SUCCESSFUL_PATTERN))
    {

        lblAuth.Text = "OK!";
    }         
}
catch
{
    lblAuth.Text = "ERROR!";
}

你能帮助我弄清楚出了什么问题吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

尝试将用户代理标头添加到您的请求中,例如:

if (client.DefaultRequestHeaders.Contains("user-agent") == false)
{
    client.DefaultRequestHeaders.Add("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)");
}

不幸的是,我无法测试您的代码,但是当HttpClient没有设置用户代理标头(或者根本没有设置它)并且网络服务器不喜欢它时,我遇到了这种情况。