我正在开发一个使用 HttpUrlConnection 的应用程序,它与服务器完美连接,但是从它获取数据时显示连接超时 IOException。
互联网和网络权限已在 android.manifest 中设置;android模拟器中没有显示条(这说明了什么)。
在 developer.android.com 上阅读:模拟器的功能限制包括: - 不支持确定网络连接状态 - 以及其他一些......
任何帮助将不胜感激。而且我没有实际的设备来测试它。
收到的服务器信息会打印在 logcat 中。
谢谢...
这是代码:
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
try {
Log.i(INFO_TAG, "Received server:" + conn.toString());
conn.setInstanceFollowRedirects(true);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-length", "0");
conn.setUseCaches(false);
conn.setAllowUserInteraction(false);
conn.setConnectTimeout(25000 /* milliseconds */);
conn.setReadTimeout(15000/* 10000 *//* milliseconds */);
// conn.setDoInput(true);
// Starts the query
conn.connect();
status = conn.getResponseCode();
Log.d(DEBUG_TAG, "Status recevied is: " + conn.getResponseCode());
responseCode = status;
if (responseCode == 200) {
Log.i(INFO_TAG, "URL Connection OK");
contentIs = conn.getInputStream();
BufferedReader reader = new BufferedReader(
new InputStreamReader(contentIs));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
Log.i(INFO_TAG, "Data Read is: " + line);
}
} else {
Log.d(DEBUG_TAG, "Could not read data from web server");
Log.e(ConnectAndGetData.class.toString(),
"Failed to download content");
}
}// end of try
catch (Exception ex) {
// This is currently being printout
Log.d(DEBUG_TAG, "Received an exception" + ex.toString(), ex);
ex.printStackTrace();
throw new IOException("Error Connecting" + ex.toString());// "Error connecting");
} finally {
if (contentIs != null) {
contentIs.close();
conn.disconnect();
}
}
还有一件事,它抛出了一个连接超时异常,它不会在这一行打印信息: Log.d(DEBUG_TAG, "Status recevied is: " + conn.getResponseCode());