HttpClient

  • Maven:
<!--https://github.com/apache/httpcomponents-client-->
<dependency>
        <groupId>org.apache.httpcomponents.core5</groupId>
        <artifactId>httpcore5</artifactId>
        <version>5.0.4</version>
</dependency>
<dependency>
        <groupId>org.apache.httpcomponents.client5</groupId>
        <artifactId>httpclient5</artifactId>
        <version>5.0.4</version>
</dependency>
  • Get,Post的封装:HttpClientUtil
import org.apache.hc.client5.http.ClientProtocolException;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.classic.methods.HttpPost;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.core5.http.ClassicHttpResponse;
import org.apache.hc.core5.http.HttpEntity;
import org.apache.hc.core5.http.HttpStatus;
import org.apache.hc.core5.http.ParseException;
import org.apache.hc.core5.http.io.HttpClientResponseHandler;
import org.apache.hc.core5.http.io.entity.EntityUtils;
import org.apache.hc.core5.http.io.entity.StringEntity;

import java.io.IOException;
import java.net.URISyntaxException;
import java.nio.charset.Charset;

public class HttpClientUtil {

    public static String doGet(String url){
        try {
            final CloseableHttpClient httpclient = HttpClients.createDefault();
            //final HttpGet httpget = new HttpGet("https://api.doctorxiong.club/v1/fund/detail?code=000001&startDate=2020-09-01");
            final HttpGet httpget = new HttpGet(url);

            System.out.println("Executing request " + httpget.getMethod() + " " + httpget.getUri());

            final HttpClientResponseHandler<String> responseHandler = new HttpClientResponseHandler<String>() {
                @Override
                public String handleResponse(
                        final ClassicHttpResponse response) throws IOException {
                    final int status = response.getCode();
                    if (status >= HttpStatus.SC_SUCCESS && status < HttpStatus.SC_REDIRECTION) {
                        final HttpEntity entity = response.getEntity();
                        try {
                            return entity != null ? EntityUtils.toString(entity) : null;
                        } catch (final ParseException ex) {
                            throw new ClientProtocolException(ex);
                        }
                    } else {
                        throw new ClientProtocolException("Unexpected response status: " + status);
                    }
                }

            };

            final String responseBody = httpclient.execute(httpget, responseHandler);

            return responseBody;
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String doPost(String url,String params){
        try {
            final CloseableHttpClient httpclient = HttpClients.createDefault();

            final HttpPost httppost = new HttpPost(url);

            StringEntity entiry = new StringEntity(params, Charset.forName("utf-8"));
            httppost.setEntity(entiry);

            httppost.setHeader("Content-Type","application/json");

            System.out.println("Executing request " + httppost.getMethod() + " " + httppost.getUri());

            final HttpClientResponseHandler<String> responseHandler = new HttpClientResponseHandler<String>() {
                @Override
                public String handleResponse(
                        final ClassicHttpResponse response) throws IOException {
                    final int status = response.getCode();
                    if (status >= HttpStatus.SC_SUCCESS && status < HttpStatus.SC_REDIRECTION) {
                        final HttpEntity entity = response.getEntity();
                        try {
                            return entity != null ? EntityUtils.toString(entity) : null;
                        } catch (final ParseException ex) {
                            throw new ClientProtocolException(ex);
                        }
                    } else {
                        throw new ClientProtocolException("Unexpected response status: " + status);
                    }
                }

            };

            final String responseBody = httpclient.execute(httppost, responseHandler);

            return responseBody;
        } catch (URISyntaxException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
  • 测试用例
String responseBody = HttpClientUtil.doGet("https://api.doctorxiong.club/v1/fund/detail?code=000001&startDate=2020-09-01");

if(responseBody != null){
      JSONObject json = JSONObject.parseObject(responseBody);
      if("200".equals(json.getString("code"))){
           System.out.println("第三方返回:" + json.getString("data"));
      }
}
JSONObject jsonObject = new JSONObject();
jsonObject.put("fundType",Arrays.asList("zs"));
jsonObject.put("sort","z");
jsonObject.put("fundCompany",Arrays.asList("80000248"));
jsonObject.put("pageIndex",1);
jsonObject.put("pageSize",1);
String responseBody = HttpClientUtil.doPost("https://api.doctorxiong.club/v1/fund/rank",JSONObject.toJSONString(jsonObject));

if(responseBody != null){
     JSONObject json = JSONObject.parseObject(responseBody);
     if("200".equals(json.getString("code"))){
           System.out.println("第三方返回:" + json.getString("data"));
     }
}

参考文档:http://hc.apache.org/httpcomponents-client-5.1.x/quickstart.html

GitHub:https://github.com/apache/httpcomponents-client

posted on 2021-08-19 14:50  陌生街中吹起褪色故梦  阅读(56)  评论(0编辑  收藏  举报