上篇文章是采用HttpUrlConnection接口进行访问,实际上Android已经为我们封装了一个HttpClient接口,这是由Apache提供的。GET方法的操作代码如下:
<pre name="code" class="java">private void surfInternet(){
//HttpGet连接对象
HttpGet httpRequest = new HttpGet("http://photocdn.sohu.com/20111123/Img326603573.jpg");
//取得HttpClient对象
HttpClient httpClient = new DefaultHttpClient();
try {
//请求HttpClient,取得HttpResponse
HttpResponse httpResponse = httpClient.execute(httpRequest);
//请求成功
if(httpResponse.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
//取得相关信息 取得HttpEntiy
HttpEntity httpEntity = httpResponse.getEntity();
InputStream is = httpEntity.getContent();
bt = BitmapFactory.decodeStream(is);
is.close();
}
} catch (Exception e) {
// TODO: handle exception
}
runOnUiThread(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
iv.setImageBitmap(bt);
}
});
}