四步走:
1、先创建一个DefaultHttpClient的实例
HttpClient httpClient=new DefaultHttpClient();
2、发送GET请求:
先创建一个HttpGet对象,传入目标的网络地址,然后调用HttpClient的execute()方法即可:
HttpGet HttpGet=new HttpGet(“http://www.baidu.com”);
httpClient.execute(httpGet);
3、返回响应实体↓
HttpResponse response
4、获取消息实体
HttpEntity entity = response.getEntity();
初步使用代码
public class HttpCLientDemo { // HttpClient 代表Http客户端 // HttpEntity 消息载体,发送或者接收消息的载体,可以通过客户端请求或者服务器响应获取实例 // HttpConnection 代表http连接 /** * @param args */ public static void main(String[] args) { // 创建默认的客户端实例 HttpClient httpCLient = new DefaultHttpClient(); // 创建get请求实例 HttpGet httpget = new HttpGet("http://www.baidu.com"); System.out.println("executing request "+httpget.getURI()); try { // 客户端执行get请求 返回响应实体 HttpResponse response = httpCLient.execute(httpget); // 服务器响应状态行 System.out.println(response.getStatusLine()); Header[] heads = response.getAllHeaders(); // 打印所有响应头 for(Header h:heads){ System.out.println(h.getName()+":"+h.getValue()); } // 获取响应消息实体 HttpEntity entity = response.getEntity(); System.out.println("------------------------------------"); if(entity != null){ //响应内容 System.out.println(EntityUtils.toString(entity)); System.out.println("----------------------------------------"); // 响应内容长度 System.out.println("响应内容长度:"+entity.getContentLength()); } } catch (ClientProtocolException e){ e.printStackTrace(); } catch (IOException e){ e.printStackTrace(); }finally{ httpCLient.getConnectionManager().shutdown(); } } }
参考资料
http://blog.csdn.net/manymore13/article/details/8481230
http://itindex.net/detail/52566-httpclient
时间: 2024-10-01 05:24:01