android网络请求中这两个类已经基本不用,大部分是用已经封装好的框架。
try {
URL url = new URL(url);
HttpURLConnection urlconn = (HttpURLConnection) url.openConnection();
urlconn.setRequestMethod("GET");
urlconn.setConnectTimeout(3 * 1000);
int code = urlconn.getResponseCode();
if (code==200){
InputStream inputStream = urlconn.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
Message msg = Message.obtain();
msg.obj=bitmap;
handler.sendMessage(msg);
}
} catch (Exception e) {
e.printStackTrace();
}
//1.创建httpclient对象
HttpClient client = new DefaultHttpClient();
//2.创建http Get请求对象
HttpGet get = new HttpGet(path);
try {
//3.使用客户端去发送get请求,服务器返回响应
HttpResponse response = client.execute(get);
//获取状态行
StatusLine line = response.getStatusLine();
if(line.getStatusCode() == 200){
//获取实体,服务器返回的数据整体视为一个实体
HttpEntity entity = response.getEntity();
InputStream is = entity.getContent();
String text = Tools.getTextFromStream(is);
Message msg = handler.obtainMessage();
msg.obj = text;
handler.sendMessage(msg);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}