刚刚使用HttpClient想稍微的总结一下。
发现引入最新版本4.5,DefaultHttpClient等老版本常用的类已经过时了,不推荐使用了;去官网看了一下在4.3之后就抛弃了。官方推荐使用 DefaultHttpClient --> CloseableHttpClient,HttpResponse --> CloseableHttpResponse 。
public static void main(String[] args) { CloseableHttpClient httpClient = null; CloseableHttpResponse response = null; //实例化CloseableHttpClient,并设置请求头 httpClient = HttpClients.custom().addInterceptorLast(new HttpRequestInterceptor() { @Override public void process(HttpRequest request, HttpContext context) throws HttpException, IOException { } }).build(); //使用Get请求方式,Post的话使用HttpPost HttpGet httpGet = new HttpGet("http://apis.baidu.com/netpopo/weather/city?apikey=9cb67c01a7268662e9347952e7e11978"); //设置请求的参数,如请求的超时时间和客户端响应的时间 RequestConfig requestConfig= RequestConfig.custom().setConnectTimeout(2000).setSocketTimeout(2000).build(); //把RequestConfig实例设置到httpget中 httpGet.setConfig(requestConfig); try { //发起请求 response = httpClient.execute(httpGet); //判断请求状态是否成功 if( response.getStatusLine().getStatusCode() == HttpStatus.SC_OK ){ //获取返回的结果 HttpEntity httpEntity = response.getEntity(); //EntityUtils.toString把返回结果抓换为字符串 System.out.println("response:"+ EntityUtils.toString(httpEntity)); } } catch (IOException e) { e.printStackTrace(); } } }