1.创建HttpClient客户端
HttpClientBuilder clientbuilder = HttpClientBuilder.create();CloseableHttpClient httpclient = clientbuilder.build();2.发送Get请求
String url = "http://www.baidu.com";HttpGet httpGet = new HttpGet(url);HttPResponse httpResponse = httpclient.execute(httpGet);3.设置超时时间RequestConfig requestconfig = RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(5000).setSocketTimeout(5000).build();httpGet.setConfig(requestconfig);4.获取响应信息实体、响应状态、响应信息HttpEntity entity = httpResponse.getEntity();StatusLine status = httpResponse.getStatusLine();if(entity!=null){ String data = EntityUtils.toString(entity);}简单的小例子:public static void main(String[] args) throws ClientProtocolException, IOException { //创建HttpClient客户端 HttpClientBuilder clientbuilder = HttpClientBuilder.create(); CloseableHttpClient httpclient = clientbuilder.build(); String url = "http://www.baidu.com"; HttpGet httpGet = new HttpGet(url); //设置超时时间 RequestConfig requestconfig = RequestConfig.custom().setConnectTimeout(5000) .setConnectionRequestTimeout(5000).setSocketTimeout(5000).build(); httpGet.setConfig(requestconfig); try{ //发送get请求 HttpResponse httpResponse = httpclient.execute(httpGet); //获取响应消息实体 HttpEntity entity = httpResponse.getEntity(); //获取响应状态 StatusLine status = httpResponse.getStatusLine(); if(entity!=null){ //获取响应信息 String data = EntityUtils.toString(entity); } }catch(IOException e){ e.printStackTrace(); }finally{ try{ httpclient.close(); }catch(IOException e){ e.printStackTrace(); } } }HttpClient4.3.1 API文档:http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/overview-summary.htmlHttpClient4.3.1相关jar包:http://pan.baidu.com/s/1qXN4Q6K
新闻热点
疑难解答