欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Java后端远程https工具类(Get和POST)

程序员文章站 2022-03-07 11:07:00
...

1、加入依赖

  <dependency>
     <groupId>org.apache.commons</groupId> 
     <artifactId>commons-lang3</artifactId> 
     </dependency>
  <dependency>
     <groupId>commons-cli</groupId> 
     <artifactId>commons-cli</artifactId> 
     <version>1.2</version> 
  </dependency>
  <dependency>
     <groupId>commons-io</groupId> 
     <artifactId>commons-io</artifactId> 
     <version>2.2</version> 
  </dependency>

2、工具类代码 

package com.example.demo.common;


import java.io.IOException;
import java.io.InputStream;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
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.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
 
@SuppressWarnings("deprecation")
public class HttpsUtils 
{ 
     
    /**
     * 向HTTPS地址发送POST请求
     * @param reqURL 请求地址
     * @param params 请求参数
     * @return 响应内容
     */ 
    @SuppressWarnings({ "finally", "resource" }) 
    public static String sendSSLPostRequest(String reqURL, Map<String, String> params)
    { 
        long responseLength = 0;                         //响应长度 
        String responseContent = null;                   //响应内容 
        HttpClient httpClient = new DefaultHttpClient(); //创建默认的httpClient实例 
        X509TrustManager xtm = new X509TrustManager()
        {   //创建TrustManager 
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} 
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} 
            public X509Certificate[] getAcceptedIssuers() { return null; } 
        }; 
        try 
        { 
            //TLS1.0与SSL3.0基本上没有太大的差别,可粗略理解为TLS是SSL的继承者,但它们使用的是相同的SSLContext 
            SSLContext ctx = SSLContext.getInstance("TLS"); 
             
            //使用TrustManager来初始化该上下文,TrustManager只是被SSL的Socket所使用 
            ctx.init(null, new TrustManager[]{xtm}, null); 
             
            //创建SSLSocketFactory 
            SSLSocketFactory socketFactory = new SSLSocketFactory(ctx); 
             
            //通过SchemeRegistry将SSLSocketFactory注册到我们的HttpClient上 
            httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory)); 
             
            HttpPost httpPost = new HttpPost(reqURL);                        //创建HttpPost 
            List<NameValuePair> formParams = new ArrayList<NameValuePair>(); //构建POST请求的表单参数 
            if(params != null)
            {
	            for(Map.Entry<String,String> entry : params.entrySet()){ 
	                formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); 
	            } 
            }
            httpPost.setEntity(new UrlEncodedFormEntity(formParams, "UTF-8")); 
             
            HttpResponse response = httpClient.execute(httpPost); //执行POST请求 
            HttpEntity entity = response.getEntity();             //获取响应实体 
             
            if (null != entity) { 
                responseLength = entity.getContentLength(); 
                responseContent = EntityUtils.toString(entity, "UTF-8"); 
                EntityUtils.consume(entity); //Consume response content 
            } 
            System.out.println("请求地址: " + httpPost.getURI()); 
            System.out.println("响应状态: " + response.getStatusLine()); 
            System.out.println("响应长度: " + responseLength); 
            System.out.println("响应内容: " + responseContent); 
        } 
        catch (Exception e) 
        { 
            e.printStackTrace(); 
        } 
        finally 
        { 
            httpClient.getConnectionManager().shutdown(); //关闭连接,释放资源 
            return responseContent; 
        } 
    } 
    
    @SuppressWarnings({ "finally", "resource" })
	public static String sendSSLPostBodyRequest(String reqURL, String bodyStr)
    { 
        long responseLength = 0;                         //响应长度 
        String responseContent = null;                   //响应内容 
        HttpClient httpClient = new DefaultHttpClient(); //创建默认的httpClient实例 
        X509TrustManager xtm = new X509TrustManager()
        {   //创建TrustManager 
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} 
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} 
            public X509Certificate[] getAcceptedIssuers() { return null; } 
        }; 
        try 
        { 
            //TLS1.0与SSL3.0基本上没有太大的差别,可粗略理解为TLS是SSL的继承者,但它们使用的是相同的SSLContext 
            SSLContext ctx = SSLContext.getInstance("TLS"); 
             
            //使用TrustManager来初始化该上下文,TrustManager只是被SSL的Socket所使用 
            ctx.init(null, new TrustManager[]{xtm}, null); 
             
            //创建SSLSocketFactory 
            SSLSocketFactory socketFactory = new SSLSocketFactory(ctx); 
             
            //通过SchemeRegistry将SSLSocketFactory注册到我们的HttpClient上 
            httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory)); 
             
            HttpPost httpPost = new HttpPost(reqURL);                        //创建HttpPost 
            if(!StringUtils.isBlank(bodyStr))
            {
	            StringEntity requestEntity = new StringEntity(bodyStr, "UTF-8");
	            httpPost.setEntity(requestEntity); 
            }
             
            HttpResponse response = httpClient.execute(httpPost); //执行POST请求 
            HttpEntity entity = response.getEntity();             //获取响应实体 
             
            if (null != entity) { 
                responseLength = entity.getContentLength(); 
                responseContent = EntityUtils.toString(entity, "UTF-8"); 
                EntityUtils.consume(entity); //Consume response content 
            } 
            System.out.println("请求地址: " + httpPost.getURI()); 
            System.out.println("响应状态: " + response.getStatusLine()); 
            System.out.println("响应长度: " + responseLength); 
            System.out.println("响应内容: " + responseContent); 
        } 
        catch (Exception e) 
        { 
            e.printStackTrace(); 
        } 
        finally 
        { 
            httpClient.getConnectionManager().shutdown(); //关闭连接,释放资源 
            return responseContent; 
        } 
    }
    
    /**
     * 向HTTPS地址发送GET请求
     * @param reqURL 请求地址
     * @param params 请求参数
     * @return 响应内容
     */ 
    @SuppressWarnings({ "finally", "resource" }) 
    public static String sendSSLGetRequest(String reqURL, Map<String, String> params)
    { 
        long responseLength = 0;                         //响应长度 
        String responseContent = null;                   //响应内容 
        HttpClient httpClient = new DefaultHttpClient(); //创建默认的httpClient实例 
        X509TrustManager xtm = new X509TrustManager()
        {   //创建TrustManager 
            public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {} 
            public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {} 
            public X509Certificate[] getAcceptedIssuers() { return null; } 
        }; 
        try 
        { 
            //TLS1.0与SSL3.0基本上没有太大的差别,可粗略理解为TLS是SSL的继承者,但它们使用的是相同的SSLContext 
            SSLContext ctx = SSLContext.getInstance("TLS"); 
             
            //使用TrustManager来初始化该上下文,TrustManager只是被SSL的Socket所使用 
            ctx.init(null, new TrustManager[]{xtm}, null); 
             
            //创建SSLSocketFactory 
            SSLSocketFactory socketFactory = new SSLSocketFactory(ctx); 
             
            //通过SchemeRegistry将SSLSocketFactory注册到我们的HttpClient上 
            httpClient.getConnectionManager().getSchemeRegistry().register(new Scheme("https", 443, socketFactory)); 
             
            HttpGet httpGet = new HttpGet(reqURL);                        //创建HttpPost 
            List<NameValuePair> formParams = new ArrayList<NameValuePair>(); //构建POST请求的表单参数 
            if(params != null)
            {
	            for(Map.Entry<String,String> entry : params.entrySet()){ 
	                formParams.add(new BasicNameValuePair(entry.getKey(), entry.getValue())); 
	            } 
            }
            try {
                HttpResponse response = httpClient.execute(httpGet);
                int statusCode = response.getStatusLine().getStatusCode();
     
                System.out.println("执行状态码 : " + statusCode);
     
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    InputStream instream = entity.getContent();
                    responseContent = IOUtils.toString(instream, "UTF-8");
                }
                System.out.println("请求地址: " + httpGet.getURI()); 
                System.out.println("响应状态: " + response.getStatusLine()); 
                System.out.println("响应长度: " + responseLength); 
                System.out.println("响应内容: " + responseContent); 
            } catch (IOException e) {
                e.printStackTrace();
            }
            
        } 
        catch (Exception e) 
        { 
            e.printStackTrace(); 
        } 
        finally 
        { 
            httpClient.getConnectionManager().shutdown(); //关闭连接,释放资源 
            return responseContent; 
        } 
    } 
 
} 

 

相关标签: https