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