Android 台灣中文網
標題:
Exception after excuting HttpResponse
[打印本頁]
作者:
albert1014
時間:
2011-11-29 00:18
標題:
Exception after excuting HttpResponse
Dear Madam/Sir,
I have some codes section as below :
-----
{
HttpClient client = new DefaultHttpClient();
StringBuilder builder = new StringBuilder();
HttpGet myget = new HttpGet("http://test123abc.comoj.com/json_test.php");
try {
HttpResponse response = client.execute(myget);
.....
}
catch (Exception e) {
Log.v("url response", "false");
e.printStackTrace();
}
}
-----
Every time I run this codes with AVD under Eclipse, it will always drop into the catch function with exception.
I tried to debug, then found that the problem happened after executing the code "HttpResponse response = client.execute(myget)".
After I saw some suggestion on internet, I added the following code in the AndroidManifest.xml which is outside of the <application> section.
" <uses-permission android:name="android.permission.INTERNET" /> "
But the same exception happens.
I want to know if there is any other reason to cause this problem.
I think this should be the simple question but I am just the beginner in Android development.
So please help me with any suggestion or checking point.
I will appreciate your any help. Thank you very much.
作者:
ploglin
時間:
2011-11-29 10:40
The following is my suggestion
public static String getInputStreamFromUrl(String remoteUrl, String chrset) {
// TODO Auto-generated method stub
isError = false;
if (cacheData.containsKey(remoteUrl)) {
Log.d(TAG, "Getting from cache file: " + remoteUrl);
return cacheData.get(remoteUrl);
}
InputStream is = null;
StringBuilder sb = new StringBuilder();
HttpURLConnection connection;
try {
URL url = new URL(remoteUrl);
Log.d(TAG, "fetch url " + remoteUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setReadTimeout(30000);
is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, chrset));
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (SocketTimeoutException e) {
Log.e(TAG, "SocketTimeoutException" + e.getMessage());
isError = true;
} catch (IOException e) {
// TODO Auto-generated catch block
Log.e(TAG, "IOException" + e.getMessage());
isError = true;
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
if (!sb.toString().equals("")) {
cacheData.put(remoteUrl, sb.toString());
}
return sb.toString();
}
複製代碼
歡迎光臨 Android 台灣中文網 (https://apk.tw/)
Powered by Discuz! X3.1