首页 > 其他分享 >HttpClient 调用工具

HttpClient 调用工具

时间:2023-04-04 10:59:35浏览次数:42  
标签:调用 http url param org import 工具 public HttpClient

package entity;

import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
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.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/*****
 * @Author: cl
 * @Description: entity
 ****/
public class HttpClient {
    private String url;
    private Map<String, String> param;
    private int statusCode;
    private String content;
    private String xmlParam;
    private boolean isHttps;

    public boolean isHttps() {
        return isHttps;
    }

    public void setHttps(boolean isHttps) {
        this.isHttps = isHttps;
    }

    public String getXmlParam() {
        return xmlParam;
    }

    public void setXmlParam(String xmlParam) {
        this.xmlParam = xmlParam;
    }

    public HttpClient(String url, Map<String, String> param) {
        this.url = url;
        this.param = param;
    }

    public HttpClient(String url) {
        this.url = url;
    }

    public void setParameter(Map<String, String> map) {
        param = map;
    }

    public void addParameter(String key, String value) {
        if (param == null)
            param = new HashMap<String, String>();
        param.put(key, value);
    }

    public void post() throws ClientProtocolException, IOException {
        HttpPost http = new HttpPost(url);
        setEntity(http);
        execute(http);
    }

    public void put() throws ClientProtocolException, IOException {
        HttpPut http = new HttpPut(url);
        setEntity(http);
        execute(http);
    }

    public void get() throws ClientProtocolException, IOException {
        if (param != null) {
            StringBuilder url = new StringBuilder(this.url);
            boolean isFirst = true;
            for (String key : param.keySet()) {
                if (isFirst) {
                    url.append("?");
                } else {
                    url.append("&");
                }
                url.append(key).append("=").append(param.get(key));
            }
            this.url = url.toString();
        }
        HttpGet http = new HttpGet(url);
        execute(http);
    }

    /**
     * set http post,put param
     */
    private void setEntity(HttpEntityEnclosingRequestBase http) {
        if (param != null) {
            List<NameValuePair> nvps = new LinkedList<NameValuePair>();
            for (String key : param.keySet()) {
                nvps.add(new BasicNameValuePair(key, param.get(key))); // 参数
            }
            http.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8)); // 设置参数
        }
        if (xmlParam != null) {
            http.setEntity(new StringEntity(xmlParam, Consts.UTF_8));
        }
    }

    private void execute(HttpUriRequest http) throws ClientProtocolException,
            IOException {
        CloseableHttpClient httpClient = null;
        try {
            if (isHttps) {
                SSLContext sslContext = new SSLContextBuilder()
                        .loadTrustMaterial(null, new TrustStrategy() {
                            // 信任所有
                            @Override
                            public boolean isTrusted(X509Certificate[] chain,
                                                     String authType)
                                    throws CertificateException {
                                return true;
                            }
                        }).build();
                SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                        sslContext);
                httpClient = HttpClients.custom().setSSLSocketFactory(sslsf)
                        .build();
            } else {
                httpClient = HttpClients.createDefault();
            }
            CloseableHttpResponse response = httpClient.execute(http);
            try {
                if (response != null) {
                    if (response.getStatusLine() != null) {
                        statusCode = response.getStatusLine().getStatusCode();
                    }
                    HttpEntity entity = response.getEntity();
                    // 响应内容
                    content = EntityUtils.toString(entity, Consts.UTF_8);
                }
            } finally {
                response.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            httpClient.close();
        }
    }

    public int getStatusCode() {
        return statusCode;
    }

    public String getContent() throws ParseException, IOException {
        return content;
    }
}

 

标签:调用,http,url,param,org,import,工具,public,HttpClient
From: https://www.cnblogs.com/chenTo/p/17285648.html

相关文章

  • vue3+vite 解决本地调用时跨域请求
    1、config配置文件中,axios默认请求地址;改为"/api",否则还是请求环境变量中的地址; 2、vite.config.ts文件中做如下配置:  server:{  open:true,//启动项目自动弹出浏览器  port:8081,//启动端口  cors:true,  proxy:{   "/api":{  ......
  • 如何找出 SAP Fiori Launchpad 里点击 tile 之后,读取业务数据调用的是哪个 SAP 后台系
    笔者曾经写过一篇文章SAPFiori应用的三种部署方式,里面介绍了SAPFiori应用部署的一种典型方式:Fiori应用的载体即SAPUI5应用,部署在Gateway系统上,也称FrontendServer(前台服务器),如下图红色方框高亮所示。当用户访问FioriLaunchpad代表SAPUI5应用的一个个tile......
  • android 调用地图
    有时候我们需要调用地图显示一下位置,这时候可能还需要导航,导航做起来有点麻烦,如果调用第三方的是不是很简单,本文就是写这个来的;第一种方式:androidIntent调用地图应用客户端调用百度地图:百度地图包:com.baidu.BaiduMaptry{intent=Intent.getIntent("intent://m......
  • 磁盘I/O性能测试工具
    测试磁盘I/O性能的工具有很多,如DD、Bonnie++、fio、iometer、hdparm等。下面简单介绍其中几个工具。1.DDDD(命令为dd)是Linux系统上一个非常流行的文件复制工具,在复制文件的同时可以根据其具体选项进行转换和格式化等操作。通过DD工具复制同一个文件(相同数据量)所需要的时间长短即可......
  • 析构函数调用次数
    #include<iostream>usingnamespacestd;classA{public:A(){cout<<"classAconstrutor"<<endl;}~A(){cout<<"classAdestrutor"<<endl;}voidfun1(){cout<<"fun1()"<<endl;}};......
  • 014redis的优化&redis工具的使用
    一、redis优化1、精简键名和键值键名:尽量精简,但是也不能单纯为了节约空间而使用不易理解的键名。键值:对于键值的数量固定的话可以使用0和1这样的数字来表示,(例如:male/female、right/wrong)2、当业务场景不需要数据持久化时,关闭所有的持久化方式可以获得最佳的性能内部编码优化(......
  • shell命令调用http接口(curl方式)
    shell命令调用http接口(curl方式) 样例1、curl-H"Content-Length:0"-XGET"http://127.0.0.1:8080"2、curl-H"Content-Type:application/json"-H"connection:Keep-Alive"-s-XPOST-d'{"id":"1"......
  • Go mod包依赖管理工具使用详解
    我个人觉得,一个包管理工具应该有以下功能:基本功能依赖管理依赖包版本控制对应的包管理平台可以私有化部署加分:代码包是否可以复用构建,测试,打包发布上线对比上面几点:目前做的最好的也就maven了,gradle没有使用过,不知道。今天主角是gomod,先来谈谈没有使用gomod之前的问题。使......
  • eyoucms 首页以及列表页内容调用标题、关键词、描述
    1、首页调用标题、关键词、描述<title>{eyou:globalname='web_title'/}</title><metaname="description"content="{eyou:globalname='web_description'/}"/><metaname="keywords"content="{eyou:g......
  • 日常生活小技巧 -- 文件对比工具 Beyond Compare
    BeyondCompare,文件对比工具,应用还是挺广泛的。下面我们讲一下它的下载安装使用方法。其实很简单!!下载:DownloadBeyondCompare4安装:以管理员身份运行,然后按照提示一步一步的安装即可,没什么好说的。使用:双击new->FolderCompare然后点击Browsefor选择要对比的文件然后进行比较然......