2
我试图制作一个Windows Phone应用程序,可以自动连接某个Wi-Fi网络上的用户。 这个应用程序已经用Java编写,所以我试图做的是“转换”C#中的Java代码。为什么我会用HTTPClient获得HttpRequestException? (C#)
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!";
}
你能帮我揣摩出了什么问题?
谢谢!
您对FORM_URL使用什么值? – 2014-09-30 15:33:34
你有404,这意味着该网址无效。如果网址在您的浏览器中运行,但不是您的代码,那么处理该网址的服务器正在检测您的“机器人”并将其阻止。 – 2014-09-30 15:33:40
您的发布请求出现问题。使用一些网络调试工具(例如,Fiddler:http://www.telerik.com/download/fiddler)并跟踪Java代码的请求/响应和您的一个。然后寻找差异。 ;) – 2014-09-30 15:36:10