java使用httpclient调用第三方接口

java使用httpclient调用第三方接口java使用httpclient调用第三方接口HttpClientUtil工具类packagecom.fz.util;importjava.io.File;importjava.net.URL;importjava.util.ArrayList;importjava.util.List;importjava.util.Map;importorg.apache.ht…

大家好,又见面了,我是你们的朋友全栈君。

java使用httpclient调用第三方接口

  1. HttpClientUtil工具类
package com.fz.util;
import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
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.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.conn.util.PublicSuffixMatcher;
import org.apache.http.conn.util.PublicSuffixMatcherLoader;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
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;
/**
* @author zy
* @version 创建时间:2018年10月17日 上午11:33:26
* @ClassName HttpClientUtil
* @Description HttpClient工具类
*/
public class HttpClientUtil {
    private RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(15000).setConnectTimeout(15000)
            .setConnectionRequestTimeout(15000).build();
    // 单例模式
    private static HttpClientUtil instance = null;

    private HttpClientUtil() {
    }

    public static HttpClientUtil getInstance() {
        if (instance == null) {
            instance = new HttpClientUtil();
        }
        return instance;
    }

    /**
     * 发送 post请求
     * 
     * @param httpUrl
     *            地址
     */
    public String sendHttpPost(String httpUrl) {
        HttpPost httpPost = new HttpPost(httpUrl);// 创建httpPost
        return sendHttpPost(httpPost);
    }

    /**
     * 发送 post请求
     * 
     * @param httpUrl
     *            地址
     * @param params
     *            参数(格式:key1=value1&key2=value2)
     */
    public String sendHttpPost(String httpUrl, String params) {
        HttpPost httpPost = new HttpPost(httpUrl);
        try {
            StringEntity stringEntity = new StringEntity(params, "UTF-9=8");
            stringEntity.setContentType("application/x-www-form-urlencoded");
            httpPost.setEntity(stringEntity);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sendHttpPost(httpPost);
    }

    /**
     * 发送 post请求
     * 
     * @param httpUrl
     *            地址
     * @param maps
     *            参数
     */
    public String sendHttpPost(String httpUrl, Map<String, String> maps) {
        HttpPost httpPost = new HttpPost(httpUrl);
        // 创建参数队列
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
        for (String key : maps.keySet()) {
            nameValuePairs.add(new BasicNameValuePair(key, maps.get(key)));
        }
        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs, "UTF-8"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sendHttpPost(httpPost);
    }

    /**
     * 发送 post请求(带文件)
     * 
     * @param httpUrl
     *            地址
     * @param maps
     *            参数
     * @param fileLists
     *            附件
     */
    public String sendHttpPost(String httpUrl, Map<String, String> maps, List<File> fileLists) {
        HttpPost httpPost = new HttpPost(httpUrl);
        MultipartEntityBuilder meBuilder = MultipartEntityBuilder.create();
        for (String key : maps.keySet()) {
            meBuilder.addPart(key, new StringBody(maps.get(key), ContentType.TEXT_PLAIN));
        }
        for (File file : fileLists) {
            FileBody fileBody = new FileBody(file);
            meBuilder.addPart("files", fileBody);
        }
        HttpEntity reqEntity = meBuilder.build();
        httpPost.setEntity(reqEntity);
        return sendHttpPost(httpPost);
    }

    /**
     * 发送Post请求
     * 
     * @param httpPost
     * @return
     */
    private String sendHttpPost(HttpPost httpPost) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;
        try {
            // 创建默认的httpClient实例
            httpClient = HttpClients.createDefault();
            httpPost.setConfig(requestConfig);
            // 执行请求
            response = httpClient.execute(httpPost);
            entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return responseContent;
    }

    /**
     * 发送 get请求
     * 
     * @param httpUrl
     */
    public String sendHttpGet(String httpUrl) {
        HttpGet httpGet = new HttpGet(httpUrl);
        return sendHttpGet(httpGet);
    }

    /**
     * 发送 get请求Https
     * 
     * @param httpUrl
     */
    public String sendHttpsGet(String httpUrl) {
        HttpGet httpGet = new HttpGet(httpUrl);
        return sendHttpGet(httpGet);
    }

    /**
     * 发送Get请求
     * 
     * @param httpPost
     * @return
     */
    public String sendHttpGet(HttpGet httpGet) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;
        try {
            // 创建默认的httpClient实例
            httpClient = HttpClients.createDefault();
            httpGet.setConfig(requestConfig);
            // 执行请求
            response = httpClient.execute(httpGet);
            entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return responseContent;
    }

    /**
     * 发送Get请求Https
     * 
     * @param httpPost
     * @return
     */
    private String sendHttpsGet(HttpGet httpGet) {
        CloseableHttpClient httpClient = null;
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;
        try {
            // 创建默认的httpClient实例
            PublicSuffixMatcher publicSuffixMatcher = PublicSuffixMatcherLoader
                    .load(new URL(httpGet.getURI().toString()));
            DefaultHostnameVerifier hostnameVerifier = new DefaultHostnameVerifier(publicSuffixMatcher);
            httpClient = HttpClients.custom().setSSLHostnameVerifier(hostnameVerifier).build();
            httpGet.setConfig(requestConfig);
            // 执行请求
            response = httpClient.execute(httpGet);
            entity = response.getEntity();
            responseContent = EntityUtils.toString(entity, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return responseContent;
    }
}

  1. 调用
public static String getInfosHomePagePic() {
		//接口地址
		String url = "";
		String sendHttpPost = HttpClientUtil.getInstance().sendHttpPost(url);
		return sendHttpPost;
	}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/141981.html原文链接:https://javaforall.net

(0)
上一篇 2022年5月24日 下午6:20
下一篇 2022年5月24日 下午6:20


相关推荐

  • 矩阵求逆的快速算法[通俗易懂]

    矩阵求逆的快速算法[通俗易懂]                                                                                                  作者:龚敏敏算法介绍矩阵求逆在3D程序中很常见,主要应用于求Billboard矩阵。按照定义的计算方法乘法运算,严重影响了性能。在需要大量Billboard矩阵运算时,矩阵求逆的优化能极大提高性

    2025年6月3日
    4
  • shiro面试知识点总结_jmeter面试常见问题

    shiro面试知识点总结_jmeter面试常见问题Shiro总结和常见面试题一、 什么是shiroShiro是一个强大易用的java安全框架,提供了认证、授权、加密、会话管理、与web集成、缓存等功能,对于任何一个应用程序,都可以提供全面的安全服务,相比其他安全框架,shiro要简单的多。二、 Shiro的核心概念Subject、SecurityManager、RealmSubject:主体,代表了当前“用户”,这个用户不一定是一个具体的…

    2022年10月14日
    6
  • 【PyCharm实用教程】最详细的Pycharm使用教程,你真不要进来学习一下?

    【PyCharm实用教程】最详细的Pycharm使用教程,你真不要进来学习一下?目录 1 PyCharm 的安装 2 编写代码 3 如何运行代码 4 进行代码的调试 5 进行代码测试 6 编辑已有项目 7 使用搜索和导航 8 配置版本控制系统 VCS 9 使用插件和外部工具 10 PyCharmProfe 功能 11 数据库支持 12 Profiler 性能分析 13 科学模式 14 远程开发 15 写在最后本文假设读者熟悉 Python 开发 且计算机中已安装某个版本的 Python 该教程将使用 Py

    2026年3月27日
    2
  • Java Arrays.asList()方法详解

    Java Arrays.asList()方法详解本文是对 Arrays asList 方法从源码角度进行分析 解析使用中的一些困惑 首先看 Arrays asList 的源码 publicstatic T a returnnewArr a 使用该方法可以将一个变长参数或者数组转换成 List 看似很简单但实际使用起来却会发现存在很多问题 看下面代码来发现问题

    2026年3月18日
    2
  • spss相关系数及其检验_等级相关系数法检验

    spss相关系数及其检验_等级相关系数法检验这里写目录标题SPSS的异方差检验(等级相关系数检验法)数据来源普通最小二乘法求回归方程功能快捷键合理的创建标题,有助于目录的生成如何改变文本的样式插入链接与图片如何插入一段漂亮的代码片生成一个适合你的列表创建一个表格设定内容居中、居左、居右SmartyPants创建一个自定义列表如何创建一个注脚注释也是必不可少的KaTeX数学公式新的甘特图功能,丰富你的文章UML图表FLowchart流程图导…

    2025年8月2日
    7
  • JDBC连接数据库的步骤

    JDBC连接数据库的步骤JDBC连接数据库一共有7步。1、首先加载驱动2、提供JDBC连接的URL3、创建数据库的连接4、创建一个statement执行者5、执行SQL语句6、处理返回结果7、关闭JDBC对象

    2022年7月4日
    28

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号