HTTP接口调用工具类 post

本文介绍了一个用于发送HTTP请求的Java工具类,包括GET、POST、PUT和HTTPS请求的实现。该工具类提供了多种参数传递方式,如字符串、Map和实体对象,并处理了连接超时、响应实体解析等问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.chinacreator.util;

import java.io.IOException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

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.client.methods.HttpPut;
import org.apache.http.client.methods.HttpRequestBase;
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.DefaultHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.util.PublicSuffixMatcher;
import org.apache.http.conn.util.PublicSuffixMatcherLoader;
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.util.EntityUtils;

public class HttpClientUtil {
    private RequestConfig requestConfig = RequestConfig.custom()  
            .setSocketTimeout(10000)  
            .setConnectTimeout(10000)  
            .setConnectionRequestTimeout(10000)  
            .build();  
      
    private static HttpClientUtil instance = null;  
    private HttpClientUtil(){}  
    public static HttpClientUtil getInstance(){  
        if (instance == null) {  
            instance = new HttpClientUtil();  
        }  
        return instance;  
    }  
      
    /** 
     * 
     * @param httpUrl 
     */  
    public String sendHttpPost(String httpUrl) {  
        HttpPost httpPost = new HttpPost(httpUrl);// 鍒涘缓httpPost    
        if(httpUrl.startsWith("https")){
            return sendHttpsPost(httpPost);  
        }else{
            return sendHttpPost(httpPost);  
        }  
    }  
      
    /** 
     * 
     * @param httpUrl 
     * @param params (:key1=value1&key2=value2) 
     */  
    public String sendHttpPost(String httpUrl, String params) {  
        HttpPost httpPost = new HttpPost(httpUrl);// 鍒涘缓httpPost    
        try {  
         
            StringEntity stringEntity = new StringEntity(params, "UTF-8");  
            stringEntity.setContentType("application/x-www-form-urlencoded");  
            httpPost.setEntity(stringEntity);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        if(httpUrl.startsWith("https")){
            return sendHttpsPost(httpPost);  
        }else{
            return sendHttpPost(httpPost);  
        }
    }  
    
    
    /** 
     * 
     * @param httpUrl 
     * @param params (:key1=value1&key2=value2) 
     */  
    public String sendHttpPostjson(String httpUrl, String params) {  
        HttpPost httpPost = new HttpPost(httpUrl);// 鍒涘缓httpPost    
        try {  
           
            StringEntity stringEntity = new StringEntity(params, "UTF-8");  
            stringEntity.setContentType("application/json");  
            httpPost.setEntity(stringEntity);  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        if(httpUrl.startsWith("https")){
            return sendHttpsPost(httpPost);  
        }else{
            return sendHttpPost(httpPost);  
        } 
    } 
      
    /** 
     * 
     * @param httpUrl 
     * @param maps
     */  
    public String sendHttpPost(String httpUrl, Map<String, String> maps) {  
        HttpPost httpPost = new HttpPost(httpUrl);// httpPost    
        // 
        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();  
        }  
        if(httpUrl.startsWith("https")){
            return sendHttpsPost(httpPost);  
        }else{
            return sendHttpPost(httpPost);  
        }
    }  
    /** 
     * 
     * @param httpUrl  
     * @param maps 
     */  
    public String sendHttpPost(HttpPost httpPost, Map<String, String> maps) {  
        // 
        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);
    }  
      
    public String sendHttpsPost(HttpPost httpPost) {
        CloseableHttpResponse response = null;
        HttpEntity entity = null;
        String responseContent = null;
        CloseableHttpClient httpClient = null;

        try {
            SSLContext sslcontext = createIgnoreVerifySSL();

            
            Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder
                    .<ConnectionSocketFactory> create()
                    .register("http", PlainConnectionSocketFactory.INSTANCE)
                    .register("https",
                            new SSLConnectionSocketFactory(sslcontext)).build();
            PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(
                    socketFactoryRegistry);
            HttpClients.custom().setConnectionManager(connManager);

            // httpclient
            httpClient = HttpClients.custom().setConnectionManager(connManager)
                    .build();
            
            httpPost.setConfig(requestConfig);
            response = httpClient.execute(httpPost);
            entity = response.getEntity();
            if(entity!=null){
                responseContent = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (response != null) {
                    response.close();
                }
                if (httpClient != null) {
                    httpClient.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return responseContent;

    }
 
      
    /** 
     * @param httpPost 
     * @return 
     */  
    public String sendHttpPost(HttpPost httpPost) {  
        CloseableHttpClient httpClient = null;  
        CloseableHttpResponse response = null;  
        HttpEntity entity = null;  
        String responseContent = null;  
        try {  
            httpClient = HttpClients.createDefault();  
            httpPost.setConfig(requestConfig);  
            response = httpClient.execute(httpPost); 
            entity = response.getEntity();  
            if(entity!=null){
                responseContent = EntityUtils.toString(entity, "UTF-8");  
            }
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                if (response != null) {  
                    response.close();  
                }  
                if (httpClient != null) {  
                    httpClient.close();  
                }  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
        return responseContent;  
    }  
  
    /** 
     * @param httpUrl 
     */  
    public String sendHttpGet(String httpUrl) {  
        HttpGet httpGet = new HttpGet(httpUrl);
        return sendHttpGet(httpGet);  
    }  
      
    /** 
     * @param httpUrl 
     */  
    public String sendHttpsGet(String httpUrl) {  
        HttpGet httpGet = new HttpGet(httpUrl);
        return sendHttpsGet(httpGet);  
    }  
      
    /** 
     * @param httpPost 
     * @return 
     */  
    public String sendHttpGet(HttpGet httpGet) {  
        CloseableHttpClient httpClient = null;  
        CloseableHttpResponse response = null;  
        HttpEntity entity = null;  
        String responseContent = null;  
        try {  
            httpClient = HttpClients.createDefault();  
            httpGet.setConfig(requestConfig);  
            response = httpClient.execute(httpGet);  
            entity = response.getEntity();  
            if(entity!=null){
                responseContent = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                if (response != null) {  
                    response.close();  
                }  
                if (httpClient != null) {  
                    httpClient.close();  
                }  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
        return responseContent;  
    } 
    
    
    
    
    /** 
     * @param httpPost 
     * @return 
     */  
    public String sendHttp(HttpRequestBase http) {  
        CloseableHttpClient httpClient = null;  
        CloseableHttpResponse response = null;  
        HttpEntity entity = null;  
        String responseContent = null;  
        try {  
            httpClient = HttpClients.createDefault();  
            http.setConfig(requestConfig);  
            response = httpClient.execute(http);  
            entity = response.getEntity();  
            if(entity!=null){
                responseContent = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                if (response != null) {  
                    response.close();  
                }  
                if (httpClient != null) {  
                    httpClient.close();  
                }  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
        return responseContent;  
    }
    
      
    /** 
     * @param httpPost 
     * @return 
     */  
    public String sendHttpsGet(HttpGet httpGet) {  
        CloseableHttpClient httpClient = null;  
        CloseableHttpResponse response = null;  
        HttpEntity entity = null;  
        String responseContent = null;  
        try {  
            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(); 
            if(entity!=null){
                responseContent = EntityUtils.toString(entity, "UTF-8");
            }
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                if (response != null) {  
                    response.close();  
                }  
                if (httpClient != null) {  
                    httpClient.close();  
                }  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
        return responseContent;  
    }  
    
    
    private static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {  
        
        SSLContext sc = SSLContext.getInstance("SSLv3");
        
        X509TrustManager trustManager = new X509TrustManager() {  
            @Override  
            public void checkClientTrusted(  
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,  
                    String paramString) throws CertificateException {  
            }  
      
            @Override  
            public void checkServerTrusted(  
                    java.security.cert.X509Certificate[] paramArrayOfX509Certificate,  
                    String paramString) throws CertificateException {  
            }  
      
            @Override  
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {  
                return null;  
            }  
        };  
      
        sc.init(null, new TrustManager[] { trustManager }, null);  
        return sc;  
    } 
        
    /**
     * httpPut
     */
    public String sendHttpPut(HttpPut httpPut) {  
        CloseableHttpClient httpClient = null;  
        CloseableHttpResponse response = null;  
        HttpEntity entity = null;  
        String responseContent = null;  
        try {  
            httpClient = HttpClients.createDefault();  
            httpPut.setConfig(requestConfig);  
            response = httpClient.execute(httpPut); 
            entity = response.getEntity();  
            if(entity!=null){
                responseContent = EntityUtils.toString(entity, "UTF-8");  
            }
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            try {  
                if (response != null) {  
                    response.close();  
                }  
                if (httpClient != null) {  
                    httpClient.close();  
                }  
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
        return responseContent;  
    }
}
 

 

调用代码(post接口)

在postman中调用成功即可用此util调用

String result = HttpClientUtil.getInstance().sendHttpPost("http://www.baidu.com?sn=f1&ak=1ab85e43d0&page=1&rows=20");

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值