gpt4 book ai didi

c# - 为什么使用 HTTPClient 会得到 HttpRequestException? (C#)

转载 作者:太空宇宙 更新时间:2023-11-03 15:50:16 26 4
gpt4 key购买 nike

我正在尝试制作一个 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# 代码没有。我在 response.EnsureSuccessStatusCode();

上遇到异常

System.Net.HttpRequestException: "Response status code does not indicate success: 404 (Not Found)."

代码如下:

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!";
}

你能帮我找出问题所在吗?

谢谢!

最佳答案

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

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 没有设置用户代理 header (或者根本没有设置)并且网络服务器不喜欢它的情况。

关于c# - 为什么使用 HTTPClient 会得到 HttpRequestException? (C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26124617/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com