java https请求,https请求如何调用

  • Post author:
  • Post category:java


https协议(Secure Hypertext Transfer Protocol) :

安全超文本传输协议, HTTPS以保密为目标研发, 简单讲HTTPS协议是由SSL+HTTP协议构建的可进行加密传输、 身份认证的网络协议, 其安全基础是SSL协议, 因此加密的详细内容请看SSL。 全称Hypertext Transfer Protocol overSecure Socket Layer。句法类同http:体系。 用于安全的HTTP数据传输。 https:URL表明它使用了HTTP, 但HTTPS存在不同于HTTP的默认端口及一个加密/身份验证层(在HTTP与TCP之间)。

HTTPS和HTTP的区别:

一、 https协议需要到ca申请证书, 一般免费证书很少, 需要交费。

二、 http是超文本传输协议, 信息是明文传输, https 则是具有安全性的ssl加密传输协议。

三、 http和https使用的是完全不同的连接方式, 用的端口也不一样, 前者是80,后者是443。

四、 http的连接很简单, 是无状态的; HTTPS协议是由SSL+HTTP协议构建的可进行加密传输、 身份认证的网络协议, 比http协议安全。


问题描述:

当在网页中访问http请求的时候网页会自动将http请求转换为https请求 并提示如下:

并且采用http那个链接采用postman请求接口时不通,那么可将原接口修改为https的请求 测试成功。

那么代码中如何调用呢?

直接上代码 工具类如下:

import java.io.IOException;
import java.nio.charset.Charset;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLContext;

import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
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.HttpPost;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpsUtils {
    private static Logger logger = LoggerFactory.getLogger(HttpsUtils.class);
    static CloseableHttpClient httpClient;
    static CloseableHttpResponse httpResponse;

    public static CloseableHttpClient createSSLClientDefault() {
        try {
            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
                // 信任所有
                public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
                    return true;
                }
            }).build();
            HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
            return HttpClients.custom().setSSLSocketFactory(sslsf).build();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyStoreException e) {
            e.printStackTrace();
        }
        return HttpClients.createDefault();

    }

    /**
     * 发送https请求
     *
     * @throws Exception
     */
    public static String sendByHttp(JSONObject jsonObject, String url) {
        try {

            HttpPost httpPost = new HttpPost(url);

            httpPost.addHeader("Content-type", "application/json; charset=utf-8");
            httpPost.setHeader("Accept", "application/json");
            httpPost.setEntity(new StringEntity(jsonObject.toString(), Charset.forName("UTF-8")));
            httpClient = HttpsUtils.createSSLClientDefault();
            httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity != null) {
                String jsObject = EntityUtils.toString(httpEntity, "UTF-8");
                return jsObject;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                httpResponse.close();
                httpClient.close();
                logger.info("请求流关闭完成");
            } catch (IOException e) {
                logger.info("请求流关闭出错");
                e.printStackTrace();
            }
        }
    }
    
     /**
     * 发送https get请求
     *
     * @throws Exception
     */
    public static String sendByHttpGet(Map<String, Object> params, String url) {
        try {
            URIBuilder uriBuilder = new URIBuilder(url);
            if(MapUtils.isNotEmpty(params)) {
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    uriBuilder.setParameter(entry.getKey(), entry.getValue().toString());
                }
            }
            HttpGet httpGet = new HttpGet(uriBuilder.build());
            httpGet.addHeader("Content-type", "application/json; charset=utf-8");
            httpGet.setHeader("Accept", "application/json");
            httpClient = HttpsUtils.createSSLClientDefault();
            httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            if (httpEntity != null) {
                String jsObject = EntityUtils.toString(httpEntity, "UTF-8");
                return jsObject;
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                httpResponse.close();
                httpClient.close();
                logger.info("请求流关闭完成");
            } catch (IOException e) {
                logger.info("请求流关闭出错");
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws Exception {
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("idCard","***");
        jsonObject.put("peopleName","***");
        System.out.println(HttpsUtils.sendByHttp(jsonObject, "https://60.214.234.91/sam/*/*/*"));;
    }

}

经测试 调用成功!

之前一直采用RestTemplate调用没有成功 ! 有用这个调用成功的可在评论区指点一下,学习学习 感谢各路大神!



版权声明:本文为IT_51888_liang原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。