我有一个 Android 应用程序,它调用部署在我的笔记本电脑上的 Apache 服务器上的 java 服务器应用程序。 在家测试应用程序时,对服务器的所有调用均成功。
但是,如果我连接到不同的 WiFi(例如在咖啡馆中),则来自应用程序(来自 Android 客户端应用程序)的调用将失败,且不会出现任何错误。
直接从浏览器向服务器发出请求可以正常工作。
用于发出请求的 Android 代码:
class LoginRequestTask extends AsyncTask<String, String, String> {
/*
* Metoda doInBackground() ruleaza pe thread-ul de fundal, in aceasta
* medoda executandu-se request-ul la server pentru logare.
*/
@Override
protected String doInBackground(String... uri) {
String output = null;
try {
String loginUrl = Globals.LoginServletUrl
+ "?operation=login&emailAddress="
+ mTxtEmail.getText() + "&password="
+ mTxtPassword.getText();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(loginUrl);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
output = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return output;
}
/*
* Metoda onPostExecute() este apelata pe thread-ul UI după ce se
* termină thread-ul de fundal. Este nevoie ca parametrul rezultat de la
* metoda doInBackground(), verificandu-se daca s-a efectuat cu succes
* logarea.
*/
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Get response
if (result != null && result.equals("true")) {
PrefUtils
.saveToPrefs(LoginActivity.this,
PrefUtils.SESSION_EMAIL, mTxtEmail.getText()
.toString());
Intent i = new Intent(getApplicationContext(), HomeScreen.class);
startActivity(i);
Toast.makeText(getApplicationContext(), "Logare cu succes.",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(),
"Logarea nu a fost realizata.", Toast.LENGTH_SHORT)
.show();
}
}
}
执行的最后一行是:
HttpResponse httpResponse = httpClient.execute(httpGet);
此后,什么也没有发生。不会引发任何异常,并且不会触发 onPostExecute 方法。
互联网权限已在我的 Android 应用程序中设置,当然,尝试时手机具有有效的网络连接。
对正在发生的事情有什么想法吗?
谢谢。
最佳答案
您的笔记本电脑可能检测到它现在位于公共(public)网络上,因此它的内置防火墙正在阻止入站连接(这就是它可以在家庭/专用网络中工作的原因)。如果超时设置为无限,则症状不会发生。尝试禁用防火墙或设置连接超时。
关于java - Android 应用程序中的 HttpClient 请求失败,没有任何异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29926295/