Java代码实现http和https请求

代码用到的 HttpClientUtils 工具类和 HttpsClientUtils 工具类放最下方

发送http请求推送用户信息

pushUserUrl在application配置
pushCaApply:
pushUserUrl: http://xxx.xxx.x.xxx:xxxx/xxxxx
updateUserUrl: http://xxx.xxx.x.xxx:xxxx/xxxxx

@Value("${pushCaApply.pushUserUrl}")
private String pushUserUrl;

@PostMapping("/register")
@ResponseBody
public AjaxResult ajaxRegister(SysUser user) {
	//注册用户添加到用户表
	xxx
	xxx
	xxx
	//通过http协议推送用户
	try {
		JSONObject pusObj = new JSONObject();
		pusObj.put("loginName", user.getLoginName());
		pusObj.put("password", password);
		pusObj.put("phone", user.getPhonenumber());
		JSONObject jsonObject = HttpClientUtils.httpPost(pushUserUrl, pusObj);
		if (!jsonObject.get("code").equals(0)){
			//推送失败将注册用户删除
   			userService.deleteUserById(deluser.getUserId());
    		return error("推送到在线受理系统不成功,注册失败!原因:" + jsonObject.get("msg"));
		}
	} catch (Exception e) {
    	return error(e.getMessage());
    }
}

发送https请求推送用户信息

pushUserUrl在application配置:
pushCaApply:
pushUserUrl: http://xxx.xxx.x.xxx:xxxx/xxxxx
updateUserUrl: http://xxx.xxx.x.xxx:xxxx/xxxxx

@Value("${pushCaApply.pushUserUrl}")
private String pushUserUrl;

@PostMapping("/register")
@ResponseBody
public AjaxResult ajaxRegister(SysUser user) {
	//注册用户添加到用户表
	xxx
	xxx
	xxx
	//通过https协议推送用户
	try {
		List<JSONObject> list = new LinkedList<>();
        JSONObject pusObj = new JSONObject();
        pusObj.put("cn", user.getUserName());
        pusObj.put("cardID", user.getCardNo());
        pusObj.put("iphone", user.getPhonenumber());
        pusObj.put("appCode", appXtCode);
        list.add(pusObj);
        String res = HttpsClient.doPost(pushUserUrl, list.toString());
        if (StringUtils.isNotEmpty(res) && JsonUtils.isJson(res)) {
            JSONObject resObj = JSONObject.parseObject(res);
            String resultCode = resObj.getString("status");
            if (resultCode.equals("0")) { //成功
                String token = Base64Util.getBASE64(UUIDUtil.getUUID());
                redisUtil.set(token, loginName, 3);
                redisUtil.expire(token, 86400, 3);
            } else {
                userService.deleteUserById(deluser.getUserId());
                return error("推送到协同签名不成功,注册失败!");
            }
        }
	} catch (Exception e) {
    	return error(e.getMessage());
    }
}

添加HttpClientUtils.java工具类

package com.ideabank.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.ideabank.exception.NetInformationException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.config.RequestConfig;
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.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;
import java.io.IOException;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class HttpClientUtils {
    private static Logger logger = LoggerFactory.getLogger(HttpClientUtils.class); // 日志记录

    private static RequestConfig requestConfig = null;

    static {
        // 设置请求和传输超时时间
        requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();
    }

    /**
     * post请求传输json参数
     *
     * @param url       url地址
     * @param jsonParam 参数
     * @return
     */
    public static JSONObject httpPost(String url, JSONObject jsonParam) throws NetInformationException, Exception {
        // post请求返回结果
        CloseableHttpClient httpClient = null;

        if (url.startsWith("https")) {
            // 执行 Https 请求.
            httpClient = createSSLInsecureClient();

        } else {
            // 执行 Http 请求.
            httpClient = HttpClients.createDefault();

        }

        JSONObject jsonResult = null;
        HttpPost httpPost = new HttpPost(url);
        // 设置请求和传输超时时间
        httpPost.setConfig(requestConfig);
        try {
            if (null != jsonParam) {
                // 解决中文乱码问题
                httpPost.addHeader("Content-type", "application/json; charset=utf-8");
                httpPost.setHeader("Accept", "application/json");
                StringEntity entity = new StringEntity(jsonParam.toString(), Charset.forName("UTF-8"));
                httpPost.setEntity(entity);
            }
            CloseableHttpResponse result = httpClient.execute(httpPost);
            // 请求发送成功,并得到响应
            if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String str = "";
                try {
                    // 读取服务器返回过来的json字符串数据
                    str = EntityUtils.toString(result.getEntity(), "utf-8");
                    // 把json字符串转换成json对象
                    jsonResult = JSONObject.parseObject(str);
                    System.out.println("----------========="+jsonResult.toString());
                } catch (Exception e) {
                    logger.error("post请求提交失败:" + url, e);
                }
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
            throw new NetInformationException("网络请求失败");
        } finally {
            httpPost.releaseConnection();
        }
        return jsonResult;
    }


    public static String httpPostWtihBody(String url, JSONObject jsonParam) throws Exception {
        // post请求返回结果
        CloseableHttpClient httpClient = null;

        if (url.startsWith("https")) {
            // 执行 Https 请求.
            httpClient = createSSLInsecureClient();

        } else {
            // 执行 Http 请求.
            httpClient = HttpClients.createDefault();

        }

        JSONObject jsonResult = null;
        HttpPost httpPost = new HttpPost(url);
        // 设置请求和传输超时时间
        httpPost.setConfig(requestConfig);
        if (null != jsonParam) {
            // 解决中文乱码问题
            httpPost.addHeader("Content-type", "application/json; charset=utf-8");
            httpPost.setHeader("Accept", "application/json");
            StringEntity entity = new StringEntity(jsonParam.toString(), Charset.forName("UTF-8"));
            httpPost.setEntity(entity);
        }
        CloseableHttpResponse result = httpClient.execute(httpPost);
        // 请求发送成功,并得到响应
        if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            String str = "";
            // 读取服务器返回过来的json字符串数据
            str = EntityUtils.toString(result.getEntity(), "utf-8");
            // 把json字符串转换成json对象
            return str;
        } else {
            throw new Exception("请求失败:"+result.getStatusLine().getStatusCode());
        }
    }

    /**
     * post请求传输String参数 例如:name=Jack&sex=1&type=2
     * Content-type:application/x-www-form-urlencoded
     *
     * @param url      url地址
     * @param strParam 参数
     * @return
     */
    public static JSONObject httpPost(String url, String strParam) {
        // post请求返回结果
        // post请求返回结果
        CloseableHttpClient httpClient = null;

        if (url.startsWith("https")) {
            // 执行 Https 请求.
            try {
                httpClient = createSSLInsecureClient();
            } catch (GeneralSecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } else {
            // 执行 Http 请求.
            httpClient = HttpClients.createDefault();

        }
        JSONObject jsonResult = null;
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        try {
            if (null != strParam) {
                // 解决中文乱码问题
                StringEntity entity = new StringEntity(strParam, "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/x-www-form-urlencoded");
                httpPost.setEntity(entity);
            }
            CloseableHttpResponse result = httpClient.execute(httpPost);
            // 请求发送成功,并得到响应
            if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                String str = "";
                try {
                    // 读取服务器返回过来的json字符串数据
                    str = EntityUtils.toString(result.getEntity(), "utf-8");
                    // 把json字符串转换成json对象
                    jsonResult = JSONObject.parseObject(str);
                } catch (Exception e) {
                    logger.error("post请求提交失败:" + url, e);
                }
            }
        } catch (IOException e) {
            logger.error("post请求提交失败:" + url, e);
        } finally {
            httpPost.releaseConnection();
        }
        return jsonResult;
    }

    /**
     * 发送get请求
     *
     * @param url 路径
     * @return
     */
    public static JSONObject httpGet(String url) {
        // get请求返回结果
        JSONObject jsonResult = null;
        // post请求返回结果
        CloseableHttpClient client = null;

        if (url.startsWith("https")) {
            // 执行 Https 请求.
            try {
                client = createSSLInsecureClient();
            } catch (GeneralSecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } else {
            // 执行 Http 请求.
            client = HttpClients.createDefault();

        }
        // 发送get请求
        HttpGet request = new HttpGet(url);
        request.setConfig(requestConfig);
        try {
            CloseableHttpResponse response = client.execute(request);

            // 请求发送成功,并得到响应
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 读取服务器返回过来的json字符串数据
                HttpEntity entity = response.getEntity();
                String strResult = EntityUtils.toString(entity, "utf-8");
                // 把json字符串转换成json对象
                jsonResult = JSONObject.parseObject(strResult);
            } else {
                logger.error("get请求提交失败:" + url);
            }
        } catch (IOException e) {
            logger.error("get请求提交失败:" + url, e);
        } finally {
            request.releaseConnection();
        }
        return jsonResult;
    }

    /**
     * 创建 SSL连接
     *
     * @return
     * @throws GeneralSecurityException
     */
    private static CloseableHttpClient createSSLInsecureClient() throws GeneralSecurityException {
        try {
            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, new X509HostnameVerifier() {

                @Override
                public boolean verify(String arg0, SSLSession arg1) {
                    return true;
                }

                @Override
                public void verify(String host, SSLSocket ssl)
                        throws IOException {
                }

                @Override
                public void verify(String host, X509Certificate cert)
                        throws SSLException {
                }

                @Override
                public void verify(String host, String[] cns,
                                   String[] subjectAlts) throws SSLException {
                }

            });

            return HttpClients.custom().setSSLSocketFactory(sslsf).build();

        } catch (GeneralSecurityException e) {
            throw e;
        }
    }

    public static void main(String[] arg) {
        try {
            HttpClientUtils.httpPost("https://127.0.0.1:8443/websocket_testsap2000.html", new JSONObject());
        } catch (NetInformationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public static JSONArray httpGetJSONArray(String url) {
        // get请求返回结果
        JSONArray jsonArray = null;
        // post请求返回结果
        CloseableHttpClient client = null;

        if (url.startsWith("https")) {
            // 执行 Https 请求.
            try {
                client = createSSLInsecureClient();
            } catch (GeneralSecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        } else {
            // 执行 Http 请求.
            client = HttpClients.createDefault();

        }
        // 发送get请求
        HttpGet request = new HttpGet(url);
        request.setConfig(requestConfig);
        try {
            CloseableHttpResponse response = client.execute(request);

            // 请求发送成功,并得到响应
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                // 读取服务器返回过来的json字符串数据
                HttpEntity entity = response.getEntity();
                String strResult = EntityUtils.toString(entity, "utf-8");
                // 把json字符串转换成json对象
                jsonArray = JSONObject.parseArray(strResult);
            } else {
                logger.error("get请求提交失败:" + url);
            }
        } catch (IOException e) {
            logger.error("get请求提交失败:" + url, e);
        } finally {
            request.releaseConnection();
        }
        return jsonArray;
    }

}

添加HttpClientUtils.java工具类

package com.ideabank.util;


import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;

import java.net.URL;
import javax.net.ssl.*;

import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.apache.commons.lang3.StringUtils;

/**
 * 发送https请求 工具类
 * 注意:是Https请求,若是Http,请将 HttpsURLConnection ---> HttpURLConnection
 */
public class HttpsClient {


    private static final Logger log = LoggerFactory.getLogger(HttpsClient.class);

    private static String              contentType;
    private static String              charset;            //编码  默认:"UTF-8"

    //[强制]在实现的HostnameVerifier子类中,需要使用verify函数效验服务器主机名的合法性,否则会导致恶意程序利用中间人攻击绕过主机名效验。
    //信任固定ip
    static {
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String hostname, SSLSession session) {
                // ip address of the service URL(like.23.28.244.244)
                if (hostname.equals("127.0.0.1xx")) {
                    return true;
                }
                return false;
            }
        });
    }

    //通过重写TrustManager的checkClientTrusted(检查客户端证书信任)和checkServerTrusted(检查服务端证书验证)。
    //以及HostnameVerifier的verify(校验)方法即可取消对证书的所有验证。
    static HostnameVerifier _hv = new HostnameVerifier() {
        @Override
        public boolean verify(String host, SSLSession sslSession) {
            log.warn("Host===>" + host);
            log.warn("sslSession.getPeerHost====>" + sslSession.getPeerHost());
            return true;
        }
    };

    static TrustManager[] _trustCerts = new TrustManager[]{
            new X509TrustManager() {
                @Override
                public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

                }

                @Override
                public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

                }

                @Override
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }
            }
    };

    ///信任证书ssl
    static {
        try {
            HttpsURLConnection.setDefaultHostnameVerifier(_hv);
            SSLContext ctxSSL = null;
            ctxSSL = SSLContext.getInstance("SSL");
            ctxSSL.init(null, _trustCerts, null);
            HttpsURLConnection.setDefaultSSLSocketFactory(ctxSSL.getSocketFactory());
        } catch (Exception e) {
            log.error("SSL context set fail: {}", e);
        }
    }

    public HttpsClient(String contentType){
        this.contentType = contentType;
        this.charset = "UTF-8";
    }

    public void setCharset(String charset) {
        this.charset = charset;
    }

    ///发送 post 请求(有返回值)
    /**************************************************************************************************************
     * @param    strHttpsUrl      目标地址
     * @param    jsonString        参数(json格式)
     * @return   String
     ***************************************************************************************************************/
    public static String doPost(String strHttpsUrl, String jsonString) {
        String result = null;
        try {
            DataOutputStream    output = null;
            BufferedReader      reader = null;
            HttpsURLConnection  httpConnnect = null;
            try {
                //创建连接
                URL httpUrl = new URL(strHttpsUrl);
                httpConnnect = (HttpsURLConnection) httpUrl.openConnection();

                //设置连接属性
                httpConnnect.setDoOutput(true);                            //输出(发送数据)
                httpConnnect.setDoInput(true);                              //输入(接收数据)
                httpConnnect.setRequestMethod("POST");                       //设置请求方式
                httpConnnect.setUseCaches(false);                         //设置是否开启缓存,post请求时,缓存必须关掉
                httpConnnect.setInstanceFollowRedirects(true);      //设置连接是否自动处理重定向(setFollowRedirects:所用http连接;setInstanceFollowRedirects:本次连接)
                httpConnnect.setRequestProperty("Content-Type", "application/json;charset=UTF-8");   //设置提交内容类型(设置请求头)

                //开始连接
                httpConnnect.connect();
                //发送请求
                output = new DataOutputStream(httpConnnect.getOutputStream());

                //发送
                if (StringUtils.isNotBlank(jsonString)) {
                    output.write(jsonString.getBytes("UTF-8"));
                }
                output.flush();
                output.close();

                //读取响应
                reader = new BufferedReader(new InputStreamReader(httpConnnect.getInputStream(), "UTF-8"));
                String lines;
                StringBuffer stringBuffer = new StringBuffer("");
                while ((lines = reader.readLine()) != null) {
                    lines = new String(lines.getBytes());
                    stringBuffer.append(lines);
                }
                result = stringBuffer.toString();
                log.info("[doPost] 返回结果:" + result);
                reader.close();
                // 断开连接
                httpConnnect.disconnect();

            } catch (Exception e) {
                e.printStackTrace();
                log.error("[doPost] 发送post 请求失败: {}", e.getMessage());
            } finally {
                if (output != null) {
                    output.flush();
                    output.close();
                }
                if (reader != null) {
                    reader.close();
                }
                if (httpConnnect != null) {
                    httpConnnect.disconnect();
                }
            }
        } catch (Exception e) {
            log.error("[doPost] 发送post 请求失败: {}", e.getMessage());
        }
        return result;
    }

    ///发送 get 请求
    /**************************************************************************************************************
     * @param    strHttpsUrl      目标地址
     * @return 无
     ***************************************************************************************************************/
    public String doGet(String strHttpsUrl) {
        String result = null;
        log.info("[doGet] GET请求地址: {} ", strHttpsUrl);
        try {
            BufferedReader      reader = null;
            HttpsURLConnection  httpConnnect = null;
            try {
                //创建连接
                URL httpUrl = new URL(strHttpsUrl);
                httpConnnect = (HttpsURLConnection) httpUrl.openConnection();
                httpConnnect.setRequestMethod("GET");                   //设置请求方式
                httpConnnect.connect();                                         //开始连接

                //读取响应
                reader = new BufferedReader(new InputStreamReader(httpConnnect.getInputStream(), charset));
                String lines;
                StringBuffer stringBuffer = new StringBuffer("");
                while ((lines = reader.readLine()) != null) {
                    lines = new String(lines.getBytes());
                    stringBuffer.append(lines);
                }
                result = stringBuffer.toString();
                log.error("[doGet] 请求返回结果:{}" , result);

                reader.close();
                httpConnnect.disconnect();

            } catch (Exception e) {
                log.error("[doGet] 发送get 请求失败: {}", e.getMessage());
            } finally {
                if (reader != null) {
                    reader.close();
                }
                if (httpConnnect != null) {
                    httpConnnect.disconnect();
                }
            }
        } catch (Exception e) {
            log.error("[doGet] 发送get 请求失败: {}", e.getMessage());
        }
        return result;
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
当使用Java发送HTTPS请求时,可以使用HttpURLConnection类来完成。以下是一个示例代码,演示如何实现免密发送HTTPS请求: ```java import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; public class HttpsRequestExample { public static void main(String[] args) throws IOException { String url = "https://example.com"; // 替换为目标URL // 创建URL对象 URL obj = new URL(url); // 打开连接 HttpURLConnection con = (HttpURLConnection) obj.openConnection(); // 设置请求方法为GET con.setRequestMethod("GET"); // 可选:设置请求头信息 con.setRequestProperty("User-Agent", "Mozilla/5.0"); // 获取响应码 int responseCode = con.getResponseCode(); System.out.println("Response Code: " + responseCode); // 读取响应内容 BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer response = new StringBuffer(); while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); // 打印响应内容 System.out.println("Response Content: " + response.toString()); } } ``` 在上述代码中,我们使用了`URL`和`HttpURLConnection`类来创建和处理HTTPS请求。可以根据需要设置请求方法、请求头信息等。`getResponseCode()`方法用于获取响应码,`getInputStream()`方法用于获取响应内容。请将代码中的`url`替换为您要发送请求的目标URL。 注意:上述代码中的示例为GET请求,如果需要进行POST请求或发送参数,请根据实际情况进行修改。另外,如果目标URL的证书是自签名或不信任的,可能需要配置SSL证书验证。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值