为什么HTTPClient会出现HttpRequestException?(C#)

本文关键字:HttpRequestException HTTPClient 为什么 | 更新日期: 2023-09-27 18:25:03

我正在尝试制作一个Windows Phone应用程序,该应用程序可以自动连接特定Wi-Fi网络上的用户。这个应用程序已经用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#代码没有。我在响应上得到一个异常。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!";
}

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

谢谢!

为什么HTTPClient会出现HttpRequestException?(C#)

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

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没有设置用户代理标头(或者根本没有设置)并且Web服务器不喜欢它时,我遇到了这种情况。

相关文章:
  • 没有找到相关文章