/** * Project Name:httpClient * File Name:Test.java * Package Name:httpClient * Date:2017年11月9日上午8:32:00 * Copyright (c) 2017, 2692613726@qq.com All Rights Reserved. * */ package httpClient; import java.io.IOException; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; /** * ClassName:Test * Function: TODO ADD FUNCTION. * Reason: TODO ADD REASON. * Date: 2017年11月9日 上午8:32:00 * @author michael * @version * @since JDK 1.7 * @see */ public class Test { public static void main(String[] args) throws Exception, IOException { CloseableHttpClient client = HttpClients.createDefault(); //请求起始行 HttpGet get= new HttpGet("http://www.sina.com.cn/"); //请求首部--可选的,User-Agent对于一些服务器必选,不加可能不会返回正确结果 get.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:39.0) Gecko/20100101 Firefox/39.0"); //执行请求 CloseableHttpResponse response = client.execute(get); //获得起始行 System.out.println(response.getStatusLine().toString()+" "); //获取首部 Header[] hs = response.getAllHeaders(); for (Header header : hs) { System.out.println(header.getName()+" "+header.getValue()+" "); } //获取实体 HttpEntity entity = response.getEntity(); System.out.println(EntityUtils.toString(entity,"utf-8")); EntityUtils.consume(entity);//释放实体 response.close(); client.close(); } }