Java中常见的几种HttpClient调用方式

这篇具有很好参考价值的文章主要介绍了Java中常见的几种HttpClient调用方式。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

Java项目中调用第三方接口的方式有

1. 通过JDK网络类Java.net.HttpURLConnection
 
2. 通过Apache common封装HttpClient

3. 通过Apache封装好的CloseableHttpClient4. Springboot提供的RestTemplate

5. 通过OkHttp6. 通过hutool的HttpUtil

一、HttpURLConnection调用

方式一:

package com.book.xw.web.util;
 
import org.springframework.lang.Nullable;
 
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
 
 
public class HttpClientUtil {
 
    /**
     * http get请求,参数拼接在URL上
     * 实例:String url = "http://op.jw.cn/idcard/query" + "?kev=" + "&idcard=" + idCard + "&realname=" + realName;
     */
    public static String doGet(String httpUrl){
        HttpURLConnection connection = null;
        InputStream is = null;
        BufferedReader br = null;
        StringBuffer result = new StringBuffer();
        try {
            //创建连接
            URL url = new URL(httpUrl);
            connection = (HttpURLConnection) url.openConnection();
            //设置请求方式
            connection.setRequestMethod("GET");
            //设置连接超时时间
            connection.setReadTimeout(15000);
            //开始连接
            connection.connect();
            //获取响应数据
            if (connection.getResponseCode() == 200) {
                //获取返回的数据
                is = connection.getInputStream();
                if (null != is) {
                    br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                    String temp = null;
                    while (null != (temp = br.readLine())) {
                        result.append(temp);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (null != is) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //关闭远程连接
            connection.disconnect();
        }
        return result.toString();
    }
 
    /**
     * Http post请求
     */
    public static String doPost(String httpUrl, String param) {
        StringBuffer result = new StringBuffer();
        //连接
        HttpURLConnection connection = null;
        OutputStream os = null;
        InputStream is = null;
        BufferedReader br = null;
        try {
            //创建连接对象
            URL url = new URL(httpUrl);
            //创建连接
            connection = (HttpURLConnection) url.openConnection();
            //设置请求方法
            connection.setRequestMethod("POST");
            //设置连接超时时间
            connection.setConnectTimeout(15000);
            //设置读取超时时间
            connection.setReadTimeout(15000);
            //DoOutput设置是否向httpUrlConnection输出,DoInput设置是否从httpUrlConnection读入,此外发送post请求必须设置这两个
            //设置是否可读取
            connection.setDoOutput(true);
            connection.setDoInput(true);
            //设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("Content-Type","application/json;charset=utf-8");
 
            //拼装参数
            if (null != param && !param.equals("")) {
                //设置参数
                os = connection.getOutputStream();
                //拼装参数
                os.write(param.getBytes("UTF-8"));
            }
            
            //connection.connect();
            //读取响应
            if (connection.getResponseCode() == 200) {
                is = connection.getInputStream();
                if (null != is) {
                    br = new BufferedReader(new InputStreamReader(is, "GBK"));
                    String temp = null;
                    while (null != (temp = br.readLine())) {
                        result.append(temp);
                        result.append("\r\n");
                    }
                }
            }
 
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //关闭连接
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(is!=null){
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //关闭连接
            connection.disconnect();
        }
        return result.toString();
    }
}

方式二:

import com.alibaba.fastjson.JSON;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
 
/**
 * @ClassName : HttpUrlConnectionToInterface
 * @Description : jdk类HttpURLConnection调用第三方http接口
 * @Author : wj
 * @Version V1.0
 */
public class HttpUrlConnectionToInterface {
 
    /**
     * 以post方式调用对方接口方法
     * @param pathUrl
     */
    public static void doPost(String pathUrl, String data){
        OutputStreamWriter out = null;
        BufferedReader br = null;
        String result = "";
        try {
            URL url = new URL(pathUrl);
 
            //打开和url之间的连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
 
            //设定请求的方法为"POST",默认是GET
            //post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
            conn.setRequestMethod("POST");
 
            //设置30秒连接超时
            conn.setConnectTimeout(30000);
            //设置30秒读取超时
            conn.setReadTimeout(30000);
 
            // 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true, 默认情况下是false;
            conn.setDoOutput(true);
            // 设置是否从httpUrlConnection读入,默认情况下是true;
            conn.setDoInput(true);
 
            // Post请求不能使用缓存
            conn.setUseCaches(false);
 
            //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");  //维持长链接
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
 
            //连接,从上述url.openConnection()至此的配置必须要在connect之前完成,
            conn.connect();
 
            /**
             * 下面的三句代码,就是调用第三方http接口
             */
            //获取URLConnection对象对应的输出流
            //此处getOutputStream会隐含的进行connect(即:如同调用上面的connect()方法,所以在开发中不调用上述的connect()也可以)。
            out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
            //发送请求参数即数据
            out.write(data);
            //flush输出流的缓冲
            out.flush();
 
            /**
             * 下面的代码相当于,获取调用第三方http接口后返回的结果
             */
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            //构造一个字符流缓存
            br = new BufferedReader(new InputStreamReader(is));
            String str = "";
            while ((str = br.readLine()) != null){
                result += str;
            }
            System.out.println(result);
            //关闭流
            is.close();
            //断开连接,disconnect是在底层tcp socket链接空闲时才切断,如果正在被其他线程使用就不切断。
            conn.disconnect();
 
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (out != null){
                    out.close();
                }
                if (br != null){
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    /**
     * 以get方式调用对方接口方法
     * @param pathUrl
     */
    public static void doGet(String pathUrl){
        BufferedReader br = null;
        String result = "";
        try {
            URL url = new URL(pathUrl);
 
            //打开和url之间的连接
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
 
            //设定请求的方法为"GET",默认是GET
            //post与get的不同之处在于post的参数不是放在URL字串里面,而是放在http请求的正文内。
            conn.setRequestMethod("GET");
 
            //设置30秒连接超时
            conn.setConnectTimeout(30000);
            //设置30秒读取超时
            conn.setReadTimeout(30000);
 
            // 设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true, 默认情况下是false;
            conn.setDoOutput(true);
            // 设置是否从httpUrlConnection读入,默认情况下是true;
            conn.setDoInput(true);
 
            // Post请求不能使用缓存(get可以不使用)
            conn.setUseCaches(false);
 
            //设置通用的请求属性
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");  //维持长链接
            conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
 
            //连接,从上述url.openConnection()至此的配置必须要在connect之前完成,
            conn.connect();
 
            /**
             * 下面的代码相当于,获取调用第三方http接口后返回的结果
             */
            //获取URLConnection对象对应的输入流
            InputStream is = conn.getInputStream();
            //构造一个字符流缓存
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String str = "";
            while ((str = br.readLine()) != null){
                result += str;
            }
            System.out.println(result);
            //关闭流
            is.close();
            //断开连接,disconnect是在底层tcp socket链接空闲时才切断,如果正在被其他线程使用就不切断。
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (br != null){
                    br.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    public static void main(String[] args) {
        //post请求一般都是把实体对象转为Json字符串
        LocationPrintDTO locationPrintDTO = new LocationPrintDTO();
        String s = JSON.toJSONString(locationPrintDTO);
        doPost("http://127.0.0.1:9090/ZebraPrinter/locationPrint", s);
        doGet("https://weather.cma.cn/api/climate?stationid=57516");
    }
}

缺点:不能直接使用池化技术,需要自行处理输入输出流

二、apache common封装HttpClient

引入依赖
<dependency>
    <groupId>commons-httpclient</groupId>
    <artifactId>commons-httpclient</artifactId>
    <version>3.1</version>
</dependency>
实现
public class HttpClientUtil {
    public static String doGet(String url, String charset) {
        //1.生成HttpClient对象并设置参数
        HttpClient httpClient = new HttpClient();
        //设置Http连接超时为5秒
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
        //2.生成GetMethod对象并设置参数
        GetMethod getMethod = new GetMethod(url);
        //设置get请求超时为5秒
        getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 5000);
        //设置请求重试处理,用的是默认的重试处理:请求三次
        getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());
        String response = "";
        //3.执行HTTP GET 请求
        try {
            int statusCode = httpClient.executeMethod(getMethod);
            //4.判断访问的状态码
            if (statusCode != HttpStatus.SC_OK) {
                System.err.println("请求出错:" + getMethod.getStatusLine());
            }
            //5.处理HTTP响应内容
            //HTTP响应头部信息,这里简单打印
            Header[] headers = getMethod.getResponseHeaders();
            for(Header h : headers) {
                System.out.println(h.getName() + "---------------" + h.getValue());
            }
            //读取HTTP响应内容,这里简单打印网页内容
            //读取为字节数组
            byte[] responseBody = getMethod.getResponseBody();
            response = new String(responseBody, charset);
            System.out.println("-----------response:" + response);
            //读取为InputStream,在网页内容数据量大时候推荐使用
            //InputStream response = getMethod.getResponseBodyAsStream();
        } catch (HttpException e) {
            e.printStackTrace();
        } catch (IOException e) {
            //发生网络异常
            System.out.println("发生网络异常!");
        } finally {
            //6.手动释放连接
            getMethod.releaseConnection();
        }
        return response;
    }
    
    public static String doPost(String url, JSONObject json){
        HttpClient httpClient = new HttpClient();
        PostMethod postMethod = new PostMethod(url);
 
        postMethod.addRequestHeader("accept", "*/*");
        postMethod.addRequestHeader("connection", "Keep-Alive");
        //设置json格式传送
        postMethod.addRequestHeader("Content-Type", "application/json;charset=utf-8");
        //必须设置下面这个Header
        postMethod.addRequestHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");

        //添加请求参数
        postMethod.addParameter("xxx", json.getString("xxx"));
 
        String res = "";
        try {
            int code = httpClient.executeMethod(postMethod);
            if (code == 200){
                res = postMethod.getResponseBodyAsString();
                System.out.println(res);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            postMethod.releaseConnection();
        }
        return res;
    }
}
public static void main(String[] args) {
        doGet("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071", "UTF-8");
        System.out.println("-----------分割线------------");
        System.out.println("-----------分割线------------");
        System.out.println("-----------分割线------------");
 
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("commentId", "13026194071");
        doPost("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm", jsonObject);
    }

三、CloseableHttpClient

可以使用连接池保持连接,并且过期自动释放。引入jar包

引入依赖
<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.2</version>
</dependency>
实现
package com.book.xw.common.util.utils;
 
import com.alibaba.fastjson.JSON;
import org.apache.http.Header;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustSelfSignedStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
 
import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
 
public class HttpCloseableClient {
    // 池化管理
    private static PoolingHttpClientConnectionManager poolConnManager = null;
    // 它是线程安全的,所有的线程都可以使用它一起发送http请求
    private static CloseableHttpClient httpClient;
    static {
        try {
            SSLContextBuilder builder = new SSLContextBuilder();
            builder.loadTrustMaterial(null, new TrustSelfSignedStrategy());
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(builder.build());
            // 配置同时支持 HTTP 和 HTPPS
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.getSocketFactory()).register("https", sslsf).build();
            // 初始化连接管理器
            poolConnManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
            // 同时最多连接数
            poolConnManager.setMaxTotal(640);
            // 设置最大路由
            poolConnManager.setDefaultMaxPerRoute(320);
            // 初始化httpClient
            httpClient = getConnection();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
    }
 
    public static CloseableHttpClient getConnection() {
        RequestConfig config = RequestConfig.custom().setConnectTimeout(5000)
                .setConnectionRequestTimeout(5000).setSocketTimeout(5000).build();
        CloseableHttpClient httpClient = HttpClients.custom()
                // 设置连接池管理
                .setConnectionManager(poolConnManager)
                .setDefaultRequestConfig(config)
                // 设置重试次数
                .setRetryHandler(new DefaultHttpRequestRetryHandler(2, false)).build();
        return httpClient;
    }
 
    public static String httpGet(String url) {
        HttpGet httpGet = new HttpGet(url);
        CloseableHttpResponse response = null;
        try {
            response = httpClient.execute(httpGet);
            String result = EntityUtils.toString(response.getEntity());
            int code = response.getStatusLine().getStatusCode();
            if (code == HttpStatus.SC_OK) {
                return result;
            } else {
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null)
                    response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
    public static String post(String uri, Object params, Header... heads) {
        HttpPost httpPost = new HttpPost(uri);
        CloseableHttpResponse response = null;
        try {
            StringEntity paramEntity = new StringEntity(JSON.toJSONString(params));
            paramEntity.setContentEncoding("UTF-8");
            paramEntity.setContentType("application/json");
            httpPost.setEntity(paramEntity);
            if (heads != null) {
                httpPost.setHeaders(heads);
            }
            response = httpClient.execute(httpPost);
            int code = response.getStatusLine().getStatusCode();
            String result = EntityUtils.toString(response.getEntity());
            if (code == HttpStatus.SC_OK) {
                return result;
            } else {
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if(response != null) {
                    response.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }
}

非连接池连接:

import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
 
import java.io.IOException;
 
/**
 * @ClassName : CloseableHttpClientToInterface
 * @Description : Apache封装好的CloseableHttpClient
 * @Author : wj
 * @Version V1.0
 */
public class CloseableHttpClientToInterface {
    private static String tokenString = "";
    private static String AUTH_TOKEN_EXPIRED = "AUTH_TOKEN_EXPIRED";
    private static CloseableHttpClient httpClient = null;
 
    /**
     * 以get方式调用第三方接口
     * @param url
     * @return
     */
    public static String doGet(String url, String token){
        //创建HttpClient对象
        CloseableHttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet get = new HttpGet(url);
 
        try {
            if (tokenString != null && !tokenString.equals("")){
                tokenString = getToken();
            }
            //api_gateway_auth_token自定义header头,用于token验证使用
            get.addHeader("api_gateway_auth_token", tokenString);
            get.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
            HttpResponse response = httpClient.execute(get);
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                //返回json格式
                String res = EntityUtils.toString(response.getEntity());
                return res;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
 
    /**
     * 以post方式调用第三方接口
     * @param url
     * @param json
     * @return
     */
    public static String doPost(String url, JSONObject json){
 
        try {
            if (httpClient == null){
                httpClient = HttpClientBuilder.create().build();
            }
 
            HttpPost post = new HttpPost(url);
 
            if (tokenString != null && !tokenString.equals("")){
                tokenString = getToken();
            }
 
            //api_gateway_auth_token自定义header头,用于token验证使用
            post.addHeader("api_gateway_auth_token", tokenString);
            post.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
 
            StringEntity s = new StringEntity(json.toString());
            s.setContentEncoding("UTF-8");
            //发送json数据需要设置contentType
            s.setContentType("application/x-www-form-urlencoded");
            //设置请求参数
            post.setEntity(s);
            HttpResponse response = httpClient.execute(post);
 
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                //返回json格式
                String res = EntityUtils.toString(response.getEntity());
                return res;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (httpClient != null){
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }
 
    /**
     * 获取第三方接口的token
     */
    public static String getToken(){
 
        String token = "";
 
        JSONObject object = new JSONObject();
        object.put("appid", "appid");
        object.put("secretkey", "secretkey");
 
        try {
            if (httpClient == null){
                httpClient = HttpClientBuilder.create().build();
            }
            HttpPost post = new HttpPost("http://localhost/login");
 
            post.addHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.81 Safari/537.36");
 
            StringEntity s = new StringEntity(object.toString());
            s.setContentEncoding("UTF-8");
            //发送json数据需要设置contentType
            s.setContentType("application/x-www-form-urlencoded");
            //设置请求参数
            post.setEntity(s);
            HttpResponse response = httpClient.execute(post);
 
            //这里可以把返回的结果按照自定义的返回数据结果,把string转换成自定义类
            //ResultTokenBO result = JSONObject.parseObject(response, ResultTokenBO.class);
 
            //把response转为jsonObject
            JSONObject result = JSONObject.parseObject(String.valueOf(response));
            if (result.containsKey("token")){
                token = result.getString("token");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return token;
    }
 
    /**
     * 测试
     */
    public static void test(String telephone){
 
        JSONObject object = new JSONObject();
        object.put("telephone", telephone);
 
        try {
            //首先获取token
            tokenString = getToken();
            String response = doPost("http://localhost/searchUrl", object);
 
            //如果返回的结果是list形式的,需要使用JSONObject.parseArray转换
            //List<Result> list = JSONObject.parseArray(response, Result.class);
 
            System.out.println(response);
 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
    public static void main(String[] args) {
        test("12345678910");
    }

四、OkHttp3

引入依赖
<dependency>
    <groupId>com.squareup.okhttp3</groupId>
    <artifactId>okhttp</artifactId>
    <version>3.10.0</version>
</dependency>
实现
@Slf4j
public class OkHttpClient {
    private static final MediaType JSON = MediaType.parse("application/json; charset=utf-8");
 
    private volatile static okhttp3.OkHttpClient client;
 
    private static final int MAX_IDLE_CONNECTION = Integer
            .parseInt(ConfigManager.get("httpclient.max_idle_connection"));
 
    private static final long KEEP_ALIVE_DURATION = Long
            .parseLong(ConfigManager.get("httpclient.keep_alive_duration"));
 
    private static final long CONNECT_TIMEOUT = Long.parseLong(ConfigManager.get("httpclient.connectTimeout"));
 
    private static final long READ_TIMEOUT = Long.parseLong(ConfigManager.get("httpclient. "));
 
    /**
     * 单例模式(双重检查模式) 
     */
    private static okhttp3.OkHttpClient getInstance() {
        if (client == null) {
            synchronized (okhttp3.OkHttpClient.class) {
                if (client == null) {
                    client = new okhttp3.OkHttpClient.Builder()
                            .connectTimeout(CONNECT_TIMEOUT, TimeUnit.SECONDS)
                            .readTimeout(READ_TIMEOUT, TimeUnit.SECONDS)
                            .connectionPool(new ConnectionPool(MAX_IDLE_CONNECTION, KEEP_ALIVE_DURATION, TimeUnit.MINUTES))
                            .build();
                }
            }
        }
        return client;
    }
 
    public static String doPost(String url, String json) throws IOException {
        RequestBody body = RequestBody.create(JSON, json);
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        try {
            Response response = OkHttpClient.getInstance().newCall(request).execute();
            if (response.isSuccessful()) {
                String result = response.body().string();
                log.info("syncPost response = {}, responseBody= {}", response, result);
                return result;
            }
            String result = response.body().string();
            log.info("syncPost response = {}, responseBody= {}", response, result);
            throw new IOException("三方接口返回http状态码为" + response.code());
        } catch (Exception e) {
            log.error("syncPost() url:{} have a ecxeption {}", url, e);
            throw new RuntimeException("syncPost() have a ecxeption {}" + e.getMessage());
        }
    }
 
    public static String doGet(String url, Map<String, Object> headParamsMap) throws IOException {
        Request request;
        final Request.Builder builder = new Request.Builder().url(url);
        try {
            if (!CollectionUtils.isEmpty(headParamsMap)) {
                final Iterator<Map.Entry<String, Object>> iterator = headParamsMap.entrySet()
                        .iterator();
                while (iterator.hasNext()) {
                    final Map.Entry<String, Object> entry = iterator.next();
                    builder.addHeader(entry.getKey(), (String) entry.getValue());
                }
            }
            request = builder.build();
            Response response = OkHttpClient.getInstance().newCall(request).execute();
            String result = response.body().string();
            log.info("syncGet response = {},responseBody= {}", response, result);
            if (!response.isSuccessful()) {
                throw new IOException("三方接口返回http状态码为" + response.code());
            }
            return result;
        } catch (Exception e) {
            log.error("remote interface url:{} have a ecxeption {}", url, e);
            throw new RuntimeException("三方接口返回异常");
        }
    }
 
}

五、OkHttp

引入依赖
        <!--okhttp3-->
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.9.1</version>
        </dependency>
import okhttp3.*;
 
import java.io.IOException;
 
/**
 * @ClassName : OkHttpToInterface
 * @Description :
 * @Author : wj
 * @Version V1.0
 */
public class OkHttpToInterface {
 
    public static final MediaType JSON = MediaType.get("application/json; charset=utf-8");
 
    /**
     * 以get方式调用第三方接口
     * @param url
     */
    public static void doGet(String url) {
        OkHttpClient okHttpClient = new OkHttpClient();
        final Request request = new Request.Builder()
                .url(url)
                .get()//默认就是GET请求,可以不写
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println( "onFailure: ");
            }
 
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                System.out.println("onResponse: " + response.body().string());
            }
        });
    }
 
    /**
     * post请求
     * @param url
     * @param json
     */
    public static void doPost(String url, String json){
        MediaType mediaType = MediaType.parse("text/x-markdown; charset=utf-8");
        String requestBody = json;
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(mediaType, requestBody))
                .build();
        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                System.out.println("onFailure: " + e.getMessage());
            }
 
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                System.out.println(response.protocol() + " " +response.code() + " " + response.message());
                Headers headers = response.headers();
                for (int i = 0; i < headers.size(); i++) {
                    System.out.println(headers.name(i) + ":" + headers.value(i));
                }
                System.out.println("onResponse: " + response.body().string());
            }
        });
    }
 
    public static void main(String[] args) {
        doGet("http://tcc.taobao.com/cc/json/mobile_tel_segment.htm?tel=13026194071");
        doPost("https://api.github.com/markdown/raw","I am Jdqm.");
    }
}

六、RestTemplate

// 先声明bean
@Configuration
public class RestTemplateConfig {
    @Bean
    public RestTemplate restTemplate(ClientHttpRequestFactory factory){
        return new RestTemplate(factory);
    }
    @Bean
    public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(15000);
        factory.setReadTimeout(5000);
        return factory;
    }
}
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
 
/**
 * @ClassName : RestTemplateToInterface
 * @Description :
 * @Author : wj
 * @Version V1.0
 */
public class RestTemplateToInterface {
 
    @Autowired
    private RestTemplate restTemplate;
 
    /**
     * 以get方式请求第三方http接口 getForEntity
     * @param url
     * @return
     */
    public User doGetWith1(String url){
        ResponseEntity<User> responseEntity = restTemplate.getForEntity(url, User.class);
        User user = responseEntity.getBody();
        return user;
    }
 
    /**
     * 以get方式请求第三方http接口 getForObject
     * 返回值返回的是响应体,省去了我们再去getBody()
     * @param url
     * @return
     */
    public User doGetWith2(String url){
        User user  = restTemplate.getForObject(url, User.class);
        return user;
    }
 
    /**
     * 以post方式请求第三方http接口 postForEntity
     * @param url
     * @return
     */
    public String doPostWith1(String url){
        User user = new User("小白", 20);
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(url, user, String.class);
        String body = responseEntity.getBody();
        return body;
    }
 
    /**
     * 以post方式请求第三方http接口 postForEntity
     * @param url
     * @return
     */
    public String doPostWith2(String url){
        User user = new User("小白", 20);
        String body = restTemplate.postForObject(url, user, String.class);
        return body;
    }
 
    /**
     * exchange
     * @return
     */
    public String doExchange(String url, Integer age, String name){
        //header参数
        HttpHeaders headers = new HttpHeaders();
        String token = "asdfaf2322";
        headers.add("authorization", token);
        headers.setContentType(MediaType.APPLICATION_JSON);
 
        //放入body中的json参数
        JSONObject obj = new JSONObject();
        obj.put("age", age);
        obj.put("name", name);
 
        //组装
        HttpEntity<JSONObject> request = new HttpEntity<>(obj, headers);
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, request, String.class);
        String body = responseEntity.getBody();
        return body;
    }
 
}

方法可以参考官方文档APi

  • delete() 在特定的URL上对资源执行HTTP DELETE操作
  • exchange() 在URL上执行特定的HTTP方法,返回包含对象的ResponseEntity,这个对象是从响应体中映射得到的
  • execute() 在URL上执行特定的HTTP方法,返回一个从响应体映射得到的对象
  • getForEntity() 发送一个HTTP GET请求,返回的ResponseEntity包含了响应体所映射成的对象
  • getForObject() 发送一个HTTP GET请求,返回的请求体将映射为一个对象
  • postForEntity() POST 数据到一个URL,返回包含一个对象的ResponseEntity,这个对象是从响应体中映射得到的
  • postForObject() POST 数据到一个URL,返回根据响应体匹配形成的对象
  • headForHeaders() 发送HTTP HEAD请求,返回包含特定资源URL的HTTP头
  • optionsForAllow() 发送HTTP OPTIONS请求,返回对特定URL的Allow头信息
  • postForLocation() POST 数据到一个URL,返回新创建资源的URL
  • put() PUT 资源到特定的URL

七、hutool的HttpUtil

引入依赖
 <dependency>
	<groupId>cn.hutool</groupId>
	<artifactId>hutool-all</artifactId>
	<version>5.7.1</version>
</dependency>
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.http.HttpUtil;
 
import java.util.HashMap;
 
/**
 * @ClassName : HttpUtilToInterface
 * @Description :
 * @Author : wj
 * @Version V1.0
 */
public class HttpUtilToInterface {
 
    /**
     * get请求示例
     */
    public static void doGet() {
        // 最简单的HTTP请求,可以自动通过header等信息判断编码,不区分HTTP和HTTPS
        String result1 = HttpUtil.get("https://www.baidu.com");
 
        // 当无法识别页面编码的时候,可以自定义请求页面的编码
        String result2 = HttpUtil.get("https://www.baidu.com", CharsetUtil.CHARSET_UTF_8);
 
        //可以单独传入http参数,这样参数会自动做URL编码,拼接在URL中
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("city", "北京");
        String result3 = HttpUtil.get("https://www.baidu.com", paramMap);
    }
 
    /**
     * post请求示例
     */
    public static void doPost() {
        //post普通请求示例
        HashMap<String, Object> paramMap = new HashMap<>();
        paramMap.put("city", "北京");
        String result= HttpUtil.post("https://www.baidu.com", paramMap);
 
        //文件上传示例
        HashMap<String, Object> paramMap1 = new HashMap<>();
        //文件上传只需将参数中的键指定(默认file),值设为文件对象即可,对于使用者来说,文件上传与普通表单提交并无区别
        paramMap1.put("file", FileUtil.file("D:\\face.jpg"));
        String result1= HttpUtil.post("https://www.baidu.com", paramMap1);
 
        //下载文件(很少用)
        String fileUrl = "http://mirrors.sohu.com/centos/8.4.2105/isos/x86_64/CentOS-8.4.2105-x86_64-dvd1.iso";
        //将文件下载后保存在E盘,返回结果为下载文件大小
        long size = HttpUtil.downloadFile(fileUrl, FileUtil.file("e:/"));
        System.out.println("Download size: " + size);
    }
}

八、自定义HttpClientUtil工具类实现(与上类似)

package com.njsc.credit.util;
 
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
 
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
 
public class HttpClientUtil {
 
	/**
	 * 带参数的get请求
	 * @param url
	 * @param param
	 * @return String
	 */
	public static String doGet(String url, Map<String, String> param) {
		// 创建Httpclient对象
		CloseableHttpClient httpclient = HttpClients.createDefault();
 
		String resultString = "";
		CloseableHttpResponse response = null;
		try {
			// 创建uri
			URIBuilder builder = new URIBuilder(url);
			if (param != null) {
				for (String key : param.keySet()) {
					builder.addParameter(key, param.get(key));
				}
			}
			URI uri = builder.build();
			// 创建http GET请求
			HttpGet httpGet = new HttpGet(uri);
			// 执行请求
			response = httpclient.execute(httpGet);
			// 判断返回状态是否为200
			if (response.getStatusLine().getStatusCode() == 200) {
				resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (response != null) {
					response.close();
				}
				httpclient.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}
	
	/**
	 * 不带参数的get请求
	 * @param url
	 * @return String
	 */
	public static String doGet(String url) {
		return doGet(url, null);
	}
 
	/**
	 * 带参数的post请求
	 * @param url
	 * @param param
	 * @return String
	 */
	public static String doPost(String url, Map<String, String> param) {
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);
			// 创建参数列表
			if (param != null) {
				List<NameValuePair> paramList = new ArrayList<>();
				for (String key : param.keySet()) {
					paramList.add(new BasicNameValuePair(key, param.get(key)));
				}
				// 模拟表单
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
				httpPost.setEntity(entity);
			}
			// 执行http请求
			response = httpClient.execute(httpPost);
			resultString = EntityUtils.toString(response.getEntity(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}
 
	/**
	 * 不带参数的post请求
	 * @param url
	 * @return String
	 */
	public static String doPost(String url) {
		return doPost(url, null);
	}
	
	/**
	 * 传送json类型的post请求
	 * @param url
	 * @param json
	 * @return String
	 */
	public static String doPostJson(String url, String json) {
		// 创建Httpclient对象
		CloseableHttpClient httpClient = HttpClients.createDefault();
		CloseableHttpResponse response = null;
		String resultString = "";
		try {
			// 创建Http Post请求
			HttpPost httpPost = new HttpPost(url);
			// 创建请求内容
			StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
			httpPost.setEntity(entity);
			// 执行http请求
			response = httpClient.execute(httpPost);
			resultString = EntityUtils.toString(response.getEntity(), "utf-8");
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				response.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return resultString;
	}
}
接口返回的数据是一个json的字符串,类型实际上是一个String字符串,要解析数据,用工具类JsonUtils的parse方法将字符串转换为Java对象,JsonUtils的代码如下:
package com.eqianxian.commons.utils.json;
 
import java.util.List;
import java.util.Map;
 
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.PropertyFilter;
import com.alibaba.fastjson.serializer.SerializerFeature;
 
/**
 * 统一使用,方便将来切换不同的JSON生成工具
 * 
 * @author wj
 * 
 */
public class JsonUtils {
	public static final int TYPE_FASTJSON = 0;
	public static final int TYPE_GSON = 1;
 
	/**
	 * <pre>
	 * 对象转化为json字符串
	 * 
	 * @param obj 待转化对象
	 * @return 代表该对象的Json字符串
	 */
	public static final String toJson(final Object obj) {
		return JSON.toJSONString(obj);
		// return gson.toJson(obj);
	}
 
	/**
	 * <pre>
	 * 对象转化为json字符串
	 * 
	 * @param obj 待转化对象
	 * @return 代表该对象的Json字符串
	 */
	public static final String toJson(final Object obj, SerializerFeature... features) {
		return JSON.toJSONString(obj, features);
		// return gson.toJson(obj);
	}
 
	/**
	 * 对象转化为json字符串并格式化
	 * 
	 * @param obj
	 * @param format 是否要格式化
	 * @return
	 */
	public static final String toJson(final Object obj, final boolean format) {
		return JSON.toJSONString(obj, format);
	}
 
	/**
	 * 对象对指定字段进行过滤处理,生成json字符串
	 * 
	 * @param obj
	 * @param fields 过滤处理字段
	 * @param ignore true做忽略处理,false做包含处理
	 * @param features json特征,为null忽略
	 * @return
	 */
	public static final String toJson(final Object obj, final String[] fields, final boolean ignore,
			SerializerFeature... features) {
		if (fields == null || fields.length < 1) {
			return toJson(obj);
		}
		if (features == null)
			features = new SerializerFeature[] { SerializerFeature.QuoteFieldNames };
		return JSON.toJSONString(obj, new PropertyFilter() {
			@Override
			public boolean apply(Object object, String name, Object value) {
				for (int i = 0; i < fields.length; i++) {
					if (name.equals(fields[i])) {
						return !ignore;
					}
				}
				return ignore;
			}
		}, features);
	}
 
	/**
	 * <pre>
	 * 解析json字符串中某路径的值
	 * 
	 * @param json
	 * @param path
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static final <E> E parse(final String json, final String path) {
		String[] keys = path.split(",");
		JSONObject obj = JSON.parseObject(json);
		for (int i = 0; i < keys.length - 1; i++) {
			obj = obj.getJSONObject(keys[i]);
		}
		return (E) obj.get(keys[keys.length - 1]);
	}
 
	/**
	 * <pre>
	 * json字符串解析为对象
	 * 
	 * @param json 代表一个对象的Json字符串
	 * @param clazz 指定目标对象的类型,即返回对象的类型
	 * @return 从json字符串解析出来的对象
	 */
	public static final <T> T parse(final String json, final Class<T> clazz) {
		return JSON.parseObject(json, clazz);
	}
 
	/**
	 * <pre>
	 * json字符串解析为对象
	 * 
	 * @param json json字符串
	 * @param path 逗号分隔的json层次结构
	 * @param clazz 目标类
	 */
	public static final <T> T parse(final String json, final String path, final Class<T> clazz) {
		String[] keys = path.split(",");
		JSONObject obj = JSON.parseObject(json);
		for (int i = 0; i < keys.length - 1; i++) {
			obj = obj.getJSONObject(keys[i]);
		}
		String inner = obj.getString(keys[keys.length - 1]);
		return parse(inner, clazz);
	}
 
	/**
	 * 将制定的对象经过字段过滤处理后,解析成为json集合
	 * 
	 * @param obj
	 * @param fields
	 * @param ignore
	 * @param clazz
	 * @param features
	 * @return
	 */
	public static final <T> List<T> parseArray(final Object obj, final String[] fields, boolean ignore,
			final Class<T> clazz, final SerializerFeature... features) {
		String json = toJson(obj, fields, ignore, features);
		return parseArray(json, clazz);
	}
 
	/**
	 * <pre>
	 * 从json字符串中解析出一个对象的集合,被解析字符串要求是合法的集合类型
	 * (形如:["k1":"v1","k2":"v2",..."kn":"vn"])
	 * 
	 * @param json - [key-value-pair...]
	 * @param clazz
	 * @return
	 */
	public static final <T> List<T> parseArray(final String json, final Class<T> clazz) {
		return JSON.parseArray(json, clazz);
	}
 
	/**
	 * <pre>
	 * 从json字符串中按照路径寻找,并解析出一个对象的集合,例如:
	 * 类Person有一个属性name,要从以下json中解析出其集合:
	 * {
	 * 	"page_info":{
	 * 		"items":{
	 * 			"item":[{"name":"KelvinZ"},{"name":"Jobs"},...{"name":"Gates"}]
	 * 	}
	 * }
	 * 使用方法:parseArray(json, "page_info,items,item", Person.class),
	 * 将根据指定路径,正确的解析出所需集合,排除外层干扰
	 * 
	 * @param json json字符串
	 * @param path 逗号分隔的json层次结构
	 * @param clazz 目标类
	 * @return
	 */
	public static final <T> List<T> parseArray(final String json, final String path, final Class<T> clazz) {
		String[] keys = path.split(",");
		JSONObject obj = JSON.parseObject(json);
		for (int i = 0; i < keys.length - 1; i++) {
			obj = obj.getJSONObject(keys[i]);
		}
		String inner = obj.getString(keys[keys.length - 1]);
		List<T> ret = parseArray(inner, clazz);
		return ret;
	}
 
	/**
	 * <pre>
	 * 有些json的常见格式错误这里可以处理,以便给后续的方法处理
	 * 常见错误:使用了\" 或者 "{ 或者 }",腾讯的页面中常见这种格式
	 * 
	 * @param invalidJson 包含非法格式的json字符串
	 * @return
	 */
	public static final String correctJson(final String invalidJson) {
		String content = invalidJson.replace("\\\"", "\"").replace("\"{", "{").replace("}\"", "}");
		return content;
	}
	/**
	 * 格式化Json
	 * 
	 * @param json
	 * @return
	 */
	public static final String formatJson(String json) {
		Map<?, ?> map = (Map<?, ?>) JSON.parse(json);
		return JSON.toJSONString(map, true);
	}
	/**
	 * 获取json串中的子json
	 * 
	 * @param json
	 * @param path
	 * @return
	 */
	public static final String getSubJson(String json, String path) {
		String[] keys = path.split(",");
		JSONObject obj = JSON.parseObject(json);
		for (int i = 0; i < keys.length - 1; i++) {
			obj = obj.getJSONObject(keys[i]);
			System.out.println(obj.toJSONString());
		}
		return obj != null ? obj.getString(keys[keys.length - 1]) : null;
	}
}
实现代码
public boolean test1(String idCard, String realName){
	String url = ......;
	logger.info("请求url:" + url);
	boolean match = false; //是否匹配
	try {
		String result = HttpClientUtil.doGet(url);
		Student stu = JsonUtils.parse(result, Student.class);
		Teacher tea = JsonUtils.parse(result, "result", Teacher.class);
		if(stu .correct() && stu .getRes() == 1){
			match = true;
		}
	} catch (Exception e) {
		e.printStackTrace();
	}
	return match;
}

十、我常用的

package com.core.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContexts;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import javax.net.ssl.SSLContext;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * @Author: wjh
 * @Date: 2022/09/14
 * @FileName: HttpClientUtil
 * @Description: HttpClientUtil
 */
public class HttpClientUtil {
    private static Logger log = LoggerFactory.getLogger(HttpClientUtil.class);

    private final static String DEFAULT_ENCODE = "UTF-8";
    /**
     * 默认 10s 超时
     */
    private static final int TIME_OUT = 10 * 1000;

    private HttpClientUtil() {
    }


    /**
     * 忽略 ssl
     *
     * @return
     */
    private static SSLContext buildIgnoreContext() {
        SSLContext sslContext = null;
        try {
            sslContext = SSLContexts.custom().setProtocol("TLSv1.2").build();
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            log.error(e.getMessage(), e);
        }

        return sslContext;
    }

    private static CloseableHttpClient getClient(int timeOut) {
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectionRequestTimeout(timeOut)
                .setConnectTimeout(timeOut)
                .setSocketTimeout(timeOut)
                .build();

        SSLContext sslContext = buildIgnoreContext();
        // 注册
        Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("http", PlainConnectionSocketFactory.INSTANCE)
                .register("https", new SSLConnectionSocketFactory(sslContext))
                .build();
        PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(registry);
        return HttpClients.custom()
                .setConnectionManager(connManager)
                .setDefaultRequestConfig(requestConfig)
                .build();
    }

    /**
     * POST application/json请求
     *
     * @param url     请求地址
     * @param jsonStr 请求数据json字符串
     * @param headers 请求头
     * @param timeOut 超时时间
     */
    public static String sendPostJson(String url, String jsonStr, Map<String, String> headers, int timeOut) {
        HttpPost post = new HttpPost(url);
        if (headers != null && headers.size() > 0) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                post.setHeader(entry.getKey(), entry.getValue());
            }
        }
        StringEntity entity = new StringEntity(jsonStr, DEFAULT_ENCODE);
        entity.setContentEncoding(DEFAULT_ENCODE);
        entity.setContentType("application/json;charset=" + DEFAULT_ENCODE);
        post.setEntity(entity);
        return execute(post, timeOut);
    }

    public static String sendDelete(String url, Map<String, String> headers, int timeOut) {

        HttpDelete httpDelete = new HttpDelete(url);
        if (headers != null && headers.size() > 0) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                httpDelete.setHeader(entry.getKey(), entry.getValue());
            }
        }
        return execute(httpDelete, timeOut);
    }

    public static String sendDelete(String url, Map<String, String> headers) {

        return sendDelete(url, headers, TIME_OUT);

    }

    /**
     * POST application/json请求
     *
     * @param url     请求地址
     * @param jsonStr 请求数据json字符串
     * @param headers 请求头
     */
    public static String sendPostJson(String url, String jsonStr, Map<String, String> headers) {
        return sendPostJson(url, jsonStr, headers, TIME_OUT);
    }

    /**
     * POST application/json请求
     *
     * @param url     请求地址
     * @param jsonStr 请求数据json字符串
     * @param timeOut 超时时间
     */
    public static String sendPostJson(String url, String jsonStr, int timeOut) {
        return sendPostJson(url, jsonStr, new HashMap<>(0), timeOut);
    }

    /**
     * POST application/json请求
     *
     * @param url     请求地址
     * @param jsonStr 请求数据json字符串
     */
    public static String sendPostJson(String url, String jsonStr) {
        return sendPostJson(url, jsonStr, TIME_OUT);
    }

    /**
     * POST application/json请求
     *
     * @param url  请求地址
     * @param data 请求数据
     */
    public static String sendPostJson(String url, Object data) {
        if (data == null) {
            data = new HashMap(0);
        }
        return sendPostJson(url, JSON.toJSONString(data));
    }

    /**
     * POST application/json请求
     *
     * @param url          请求地址
     * @param jsonStr      请求数据json字符串
     * @param responseType 返回值类型
     */
    public static <T> T postJsonForObject(String url, String jsonStr, Class<T> responseType) {
        String result = sendPostJson(url, jsonStr);
        if (StringUtils.isNotBlank(result)) {
            return JSONObject.parseObject(result, responseType);
        } else {
            return null;
        }
    }

    /**
     * POST application/json请求
     *
     * @param url          请求地址
     * @param jsonStr      请求数据json字符串
     * @param responseType 返回值类型
     */
    public static <T> T postJsonForObject(String url, String jsonStr, TypeReference<T> responseType) {
        String result = sendPostJson(url, jsonStr);
        if (StringUtils.isNotBlank(result)) {
            return JSON.parseObject(result, responseType);
        } else {
            return null;
        }
    }

    /**
     * POST application/json请求
     *
     * @param url          请求地址
     * @param data         请求数据
     * @param responseType 返回值类型
     */
    public static <T> T postJsonForObject(String url, Object data, Class<T> responseType) {
        if (data == null) {
            data = new HashMap(0);
        }
        return postJsonForObject(url, JSON.toJSONString(data), responseType);
    }

    /**
     * POST application/json请求
     *
     * @param url          请求地址
     * @param data         请求数据
     * @param responseType 返回值类型
     */
    public static <T> T postJsonForObject(String url, Object data, TypeReference<T> responseType) {
        if (data == null) {
            data = new HashMap(0);
        }
        return postJsonForObject(url, JSON.toJSONString(data), responseType);
    }


    /**
     * POST application/x-www-form-urlencoded 请求
     *
     * @param url    请求地址
     * @param params 请求数据map
     */
    public static String sendPostForm(String url, Map<String, String> params) {
        return sendPostForm(url, params, new HashMap<>(0));
    }

    /**
     * POST application/x-www-form-urlencoded 请求
     *
     * @param url     请求地址
     * @param params  请求数据map
     * @param timeOut 超时时间
     */
    public static String sendPostForm(String url, Map<String, String> params, int timeOut) {
        Map<String, String> headers = new HashMap<>(1);
        return sendPostForm(url, params, headers, timeOut);
    }

    /**
     * POST application/x-www-form-urlencoded 请求
     *
     * @param url     请求地址
     * @param params  请求数据map
     * @param headers 请求头
     */
    public static String sendPostForm(String url, Map<String, String> params, Map<String, String> headers) {
        return sendPostForm(url, params, headers, TIME_OUT);
    }

    /**
     * POST application/x-www-form-urlencoded 请求
     *
     * @param url     请求地址
     * @param params  请求数据map
     * @param headers 请求头
     * @param timeOut 超时时间
     */
    public static String sendPostForm(String url, Map<String, String> params, Map<String, String> headers, int timeOut) {
        UrlEncodedFormEntity reqEntity = createFormEntity(params);
        HttpPost httppost = new HttpPost(url);
        httppost.addHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);
        if (headers != null) {
            for (Map.Entry<String, String> entry : headers.entrySet()) {
                if (StringUtils.equalsAnyIgnoreCase
                        (entry.getKey(), HttpHeaders.CONTENT_LENGTH, HttpHeaders.CONTENT_TYPE)) {
                    continue;
                }
                httppost.addHeader(entry.getKey(), entry.getValue());
            }
        }
        httppost.setEntity(reqEntity);
        return execute(httppost, timeOut);
    }

    /**
     * POST application/x-www-form-urlencoded 请求
     *
     * @param url          请求地址
     * @param params       请求数据map
     * @param responseType 返回值类型
     */
    public static <T> T postFormForObject(String url, Map<String, String> params, Class<T> responseType) {
        String result = sendPostForm(url, params);
        if (StringUtils.isNotBlank(result)) {
            return JSONObject.parseObject(result, responseType);
        } else {
            return null;
        }
    }

    /**
     * POST application/x-www-form-urlencoded 请求
     *
     * @param url          请求地址
     * @param params       请求数据map
     * @param responseType 返回值类型
     */
    public static <T> T postFormForObject(String url, Map<String, String> params, TypeReference<T> responseType) {
        String result = sendPostForm(url, params);
        if (StringUtils.isNotBlank(result)) {
            return JSON.parseObject(result, responseType);
        } else {
            return null;
        }
    }

    /**
     * GET 请求
     *
     * @param url     请求地址
     * @param params  请求参数
     * @param timeOut 超时时间
     * @return
     */
    public static String sendGet(String url, Map<String, String> params, int timeOut) {
        return sendGet(url, params, new HashMap<>(1), timeOut);
    }

    /**
     * GET 请求
     *
     * @param url    请求地址
     * @param params 请求参数
     */
    public static String sendGet(String url, Map<String, String> params) {
        return sendGet(url, params, new HashMap<>(1));
    }

    /**
     * GET 请求
     *
     * @param url     url
     * @param params  请求参数
     * @param headers 请求头
     * @param timeOut 超时时间
     */
    public static String sendGet(String url, Map<String, String> params, Map<String, String> headers, int timeOut) {
        if (url == null) {
            return null;
        }
        try {
            URIBuilder uriBuilder = new URIBuilder(url);
            if (null != params) {
                uriBuilder.setParameters(getNameValuePairList(params));
            }
            URI uri = uriBuilder.build();
            String rawQueryString = uri.getRawQuery();
            //拼接url
            if (StringUtils.isNotBlank(rawQueryString)) {
                // 防止原本url里面就有参数
                if (!url.contains("?")) {
                    url = url + "?";
                }
                if (url.endsWith("?")) {
                    url = url + rawQueryString;
                } else {
                    url = url + "&" + rawQueryString;
                }
            }
            HttpGet httpGet = new HttpGet(url);
            if (headers != null) {
                Set<Map.Entry<String, String>> entrySet = headers.entrySet();
                for (Map.Entry<String, String> entry : entrySet) {
                    httpGet.setHeader(entry.getKey(), entry.getValue());
                }
            }
            return execute(httpGet, timeOut);
        } catch (URISyntaxException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    /**
     * GET 请求
     *
     * @param url     请求地址
     * @param params  请求参数
     * @param headers 请求头
     */
    public static String sendGet(String url, Map<String, String> params, Map<String, String> headers) {
        return sendGet(url, params, headers, TIME_OUT);
    }

    /**
     * GET 请求
     *
     * @param url          请求地址
     * @param params       请求参数
     * @param responseType 返回值类型
     */
    public static <T> T getForObject(String url, Map<String, String> params, Class<T> responseType) {
        String result = sendGet(url, params);
        if (StringUtils.isNotBlank(result)) {
            return JSONObject.parseObject(result, responseType);
        } else {
            return null;
        }
    }

    /**
     * GET 请求
     *
     * @param url          请求地址
     * @param params       请求参数
     * @param responseType 返回值类型
     */
    public static <T> T getForObject(String url, Map<String, String> params, TypeReference<T> responseType) {
        String result = sendGet(url, params);
        if (StringUtils.isNotBlank(result)) {
            return JSON.parseObject(result, responseType);
        } else {
            return null;
        }
    }

    private static List<NameValuePair> getNameValuePairList(Map<String, String> params) {
        List<NameValuePair> list = new ArrayList<>();
        try {
            if (params != null && !params.isEmpty()) {
                for (String key : params.keySet()) {
                    String value = params.get(key);
                    if (value != null) {
                        list.add(new BasicNameValuePair(key, value));
                    }
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
        return list;
    }

    private static UrlEncodedFormEntity createFormEntity(Map<String, String> pram) {
        try {
            List<NameValuePair> formParams = getNameValuePairList(pram);
            return new UrlEncodedFormEntity(formParams, DEFAULT_ENCODE);
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage(), e);
        }
        return null;
    }

    private static String execute(HttpRequestBase requestBase, int timeOut) {
        StringBuilder sb = new StringBuilder();
        BufferedReader reader = null;
        CloseableHttpResponse response = null;
        CloseableHttpClient httpClient = getClient(timeOut);
        try {
            // 执行
            long start = System.currentTimeMillis();
            response = httpClient.execute(requestBase);
            log.debug("请求id: {} , url: {} , 耗时: {} ", requestBase.getURI().toString(), (System.currentTimeMillis() - start));
            HttpEntity entity = response.getEntity();
            reader = new BufferedReader(new InputStreamReader(entity.getContent(), DEFAULT_ENCODE));
            String line = reader.readLine();
            while (line != null) {
                sb.append(line);
                line = reader.readLine();
            }
            EntityUtils.consume(entity);
        } catch (Exception e) {
            log.error("远程调用异常", e);
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
                if (response != null) {
                    response.close();
                }
                httpClient.close();
            } catch (IOException e) {
                log.error("", e);
            }

        }
        return sb.toString();
    }


    /**
     * POST   multipart/form-data  请求
     *
     * @param requestUrl
     * @param body
     */
    public static String sendPostWithFile(String requestUrl, RequestBody body) {
        try {
            OkHttpClient client = new OkHttpClient().newBuilder().build();
            Request request = new Request.Builder()
                    .url(requestUrl)
                    .method("POST", body)
                    //.post(body) // 设置请求方法为POST,并传入RequestBody对象  
                    .addHeader("Content-Type", "multipart/form-data")
                    .build();
            Response response = client.newCall(request).execute();
            if (response.body() == null) {
                log.info("发送httpClent获取数据为空");
                return null;
            }
            log.info("from-data:" + response.body().toString());
            return response.body().string();
        } catch (Exception e) {
            log.info("******发送httpClent  请求出错****" + e.getMessage());
        } finally {

        }
        return null;
    }
}

post接口请求

		HashMap<Object, Object> map = new HashMap<>();
        map.put("xm", xm);
        map.put("sfzh", sfzh);
        map.put("sec", sec);
        JSONObject params = new JSONObject();
        params.put("method", "winning.hms.healthrecord.recordurl.get");
        params.put("content", map);
        log.info("入参:" + JSON.toJSONString(params));
        //String healthUrl = commonService.getSytemCode(orgnCode, "A051");
        String healthUrl = dataManager.getConfigValue(orgnCode, "A051");
        if (healthUrl == null || healthUrl.isEmpty()) {
            return message.setCode("F").setMessage("请配置Url");
        }
        String resultStr = HttpClientUtil.sendPostJson(healthUrl, params);
        if (resultStr != null && !resultStr.isEmpty()) {
            JSONObject jsonObject = JSON.parseObject(resultStr);
            if (ConstantValues.CONSTANT_1.equals(jsonObject.getString("code"))) {
                JSONObject data = jsonObject.getJSONObject("data");
                String daurl = data.getString("daurl");
                return message.setCode("T").setMessage("success").setData(daurl);
            }
        }

文件上传请求文章来源地址https://www.toymoban.com/news/detail-758624.html

import okhttp3.MediaType;  
import okhttp3.OkHttpClient;  
import okhttp3.Request;  
import okhttp3.RequestBody;  
import okhttp3.Response;  
  
import java.io.File;  
import java.io.IOException;  
import java.nio.file.Files;  
import java.nio.file.Paths; 


public class Main {  
    public static void main(String[] args) {  
        String filePath = "path/to/your/file.txt"; // 替换为你的文件路径  
        File file = new File(filePath);  
        MediaType mediaType = MediaType.parse("text/plain"); // 根据文件类型设置MediaType,此处为示例,实际应根据你的文件类型进行调整  
  
        RequestBody requestBody = new RequestBody() {  
            @Override  
            public MediaType contentType() {  
                return mediaType;  
            }
            @Override  
            public long contentLength() {  
                try {  
                    return Files.size(Paths.get(filePath));  
                } catch (IOException e) {  
                    e.printStackTrace();  
                    return 0;  
                }  
            }
            @Override  
            public void writeTo(BufferedSource source) throws IOException {  
                Files.copy(Paths.get(filePath), source);  
            }  
        };  
        String resultStr = HttpClientUtil.sendPostWithFile("http://example.com/upload", requestBody);
    }  
}

到了这里,关于Java中常见的几种HttpClient调用方式的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Java中String类的几种常见遍历方式

    今天小小的给自己总结一下String类的几种常见遍历方式,如下。 charAt(): charAt(int index) :返回 char指定索引处的值。 toCharArray() : toCharArray() :将此字符串转换为新的字符数组。 然后按照遍历字符串数组的方式遍历即可,可采用普通for循环遍历,也可以采用增强for循环遍历。 sub

    2024年02月16日
    浏览(45)
  • Linux 下通过 java 命令启动 jar 包的几种常见方式

    Linux 下通过 java 命令启动 jar 包的几种常见方式 一、后台启动jar包命令 方法一:直接启动 jar 包服务 方法二:后台启动 jar 包服务 方法三:后台不挂断启动 方式四:指定日志输出的启动 方式五:指定配置文件启动 方式六:指定配置文件,使用系统默认的log配置,不另行指定

    2024年02月13日
    浏览(43)
  • java发送http请求的几种方式,调用第三方接口的方法:HttpUtil、HttpURLConnection等

    参考:https://blog.csdn.net/yubin1285570923/article/details/126225347 put请求 post带请求头 get、delete类似… 使用JDK原生提供的net,无需其他jar包,代码如下: 需要用到commons-httpclient-3.1.jar,maven依赖如下: 看一下我实际应用的例子 需要用到httpclient-4.5.6.jar,maven依赖如下: RestTemplate 是由

    2024年01月18日
    浏览(54)
  • [最新]简易版本Java HttpClient POST请求调用OpenAI(ChatGPT3/3.5/4)相关接口核心方法(附100个OpenAI/ChatGPT key)

    前言 当下,OpenAI 存在着许多令人惊叹的技术,如 ChatGPT3/3.5/4,它们能够生成高质量的文章、翻译语言、自动生成代码,并且在许多领域都取得了广泛的应用。本文将向您介绍如何使用 Java HttpClient 调用 OpenAI 的 ChatGPT3/3.5/4 接口(如果需要支持Spring,并提供了 100 个 OpenAI/Chat

    2023年04月27日
    浏览(64)
  • java httpclient 请求

    要使用Java的HttpClient库发送HTTP请求,您需要导入相应的库并编写Java代码。HttpClient是Apache HttpComponents项目的一部分,可以使用它来执行HTTP请求。以下是一个简单的示例,演示如何使用HttpClient发送GET请求: import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; im

    2024年02月07日
    浏览(50)
  • Java HttpClient爬虫请求

    添加依赖 pom文件 GET 无参形式 GET带参请求 POST无参请求 POST带参请求

    2024年02月16日
    浏览(51)
  • Java进阶篇--HttpClient工具类

    目录 什么是HttpClient HttpClient的注意事项 HttpClient的使用流程 HttpClient常用方法 HttpClient工具类 添加依赖 HttpClient 是 Apache HttpComponents 的一个子项目,旨在提供高效的、最新的、功能丰富的 HTTP 协议客户端编程工具包。它是一个 Java 库,可用于在 Java 应用程序中发送 HTTP 请求并处

    2024年02月10日
    浏览(60)
  • Java开源工具库使用之httpclient

    HttpClient 成立于2001年,是 Apache Jakarta Commons 项目下的子项目,2004 年离开 Commons ,提升成为一个单独的 Jakarta 项目。2005 年,Jakarta 创建了 HttpComponents 项目,目标是开发 HttpClient 3.x 的继任者。2007 年, Commons 项目,也就是 HttpClient 项目的发源地,离开了 Jakarta , 成为了1个新的

    2024年02月06日
    浏览(50)
  • java后端对接外部系统(HttpClient HttpPost)

    最近遇到一个需求对接外部系统,我们自己的系统发送请求,根据请求内容的不同调用不同的外部系统。举例:我们是做互联网医院的,根据医生开处方选择药店的不同,调用各药店自己的系统,返回结果 可以学到对接外部系统的一些设计 构造需要的json java项目中HTTPPost请求

    2024年02月15日
    浏览(50)
  • 【Java-Crawler】HttpClient+Jsoup实现简单爬虫

    网络爬虫(WEB crawler),是一种按照一定的规则,自动地抓取万维网信息的程序或者脚本。 导入依赖(下面列的程序用的是这个依赖,是版本5,我是从Maven中直接copy最新版的,没想那么多,但4点多的用的人多点,而且网上资料也多点,所以还是推荐大家用4点多的吧,但是下

    2024年02月05日
    浏览(40)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包