public byte[] sendRequest(String url){
byte[] bytes = null;
HttpClient httpClient = new DefaultHttpClient();
// AndroidHttpClient httpClient = AndroidHttpClient.newInstance(userAgent, context);
HttpGet httpGet = new HttpGet (url);
Log.e(TAG, "sendRequest url = " + url);
try {
HttpResponse response = httpClient.execute(httpGet);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode != HttpStatus.SC_OK){
throw new HttpException(statusCode);
}else{
HttpEntity entity = response.getEntity();
bytes = EntityUtils.toByteArray(entity);
Log.e(TAG, "result = " + bytes.toString());
}
} catch (IOException e) {
Log.e(TAG, "GalleryService sendRequest IOException " + e.getMessage());
e.printStackTrace();
} catch (HttpException e){
Log.e(TAG, "GalleryService sendRequest HttpException " + e.getMessage());
e.printStackTrace();
} catch (Exception e){
Log.e(TAG, "GalleryService sendRequest Exception " + e.getMessage());
e.printStackTrace();
}finally{
// if(httpClient != null)
// httpClient.close();
}
return bytes;
}
This is such a bad idea that the AndroidHttpClient does not allow itself to be started from the main thread. The above code will display "This thread forbids HTTP requests" error messages instead. Use the DefaultHttpClient instead if you really want to shoot yourself in the foot.
AndroidHttpClient不能運行在UI線程,因此要從其它線程啓動,或者使用DefaultHttpClient。