项长老

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::

四步走:

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

posted on 2016-02-01 23:21  项长老  阅读(197)  评论(0编辑  收藏  举报