Apache HttpClient使用

来源:互联网 发布:电信4g网络apn设置 编辑:程序博客网 时间:2024/06/07 06:47

一 场景:

  java后台开发经常会需要发送HTTP请求,经常会使用Apache的HttpClient发送请求。

二 Post发送表单

1.设置请求参数

List<BasicNameValuePair> content = new ArrayList<BasicNameValuePair>();content.add(new BasicNameValuePair("tradingPartner", "jaden");content.add(new BasicNameValuePair("documentProtocol", "jaden"));content.add(new BasicNameValuePair("requestMessage", sw.toString()));//调用Http请求方法String result = sentHttpPostRequest(url, content);

2.发送HTTP请求

public String sentHttpPostRequest(String url, List<BasicNameValuePair> content) throws Exception {        //构建HttpClient实例        CloseableHttpClient httpclient = HttpClients.createDefault();        //设置请求超时时间        RequestConfig requestConfig = RequestConfig.custom()                .setSocketTimeout(60000)                .setConnectTimeout(60000)                .setConnectionRequestTimeout(60000)                .build();        //指定POST请求        HttpPost httppost = new HttpPost(url);        httppost.setConfig(requestConfig);        //包装请求体        List<NameValuePair> params = new ArrayList<NameValuePair>();        params.addAll(content);        HttpEntity request = new UrlEncodedFormEntity(params, "utf-8");        //发送请求        httppost.setEntity(request);        CloseableHttpResponse httpResponse = httpclient.execute(httppost);        //读取响应        HttpEntity entity = httpResponse.getEntity();        String result = null;        if (entity != null) {            result = EntityUtils.toString(entity);        }        return result;    }

说明:
1.创建可关闭的HttpClient,即 CloseableHttpClient httpclient;
2.读取响应,也是用可关闭的response,即CloseableHttpResponse httpResponse;

好处:这样可以使得创建出来的HTTP实体,可以被Java虚拟机回收掉,不至于出现一直占用资源的情况。

三 Post发送JSON字符串

大部分同上述代码相同,不同之处在于包装请求体部分:

String jsonStr = {"name":"jaden","age":"23","other":"xxx"};HttpEntity param = new StringEntity(jsonStr, "UTF-8");//设置请求体httppost.setEntity(param);

四 Get请求

使用HttpGet即可

CloseableHttpClient httpclient = HttpClients.createDefault();HttpGet request = new HttpGet(url);request.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) ...");CloseableHttpResponse response = httpclient.execute(request);// read response

日常总结,助人助己。

原创粉丝点击