http及https模拟工具使用总结及客户端及服务端模拟代码样例

 

 

一、工具介绍

1、restclient-1.2.jar 为客户端请求工具,可以调用任何的http及https的服务,可以任意调用https的网页地址(比入百度等)postman模拟的服务

 

2、HttpMockServerTool.jar

只能模拟http的 服务端,不能模拟https的。

 

需要自己造个 返回响应文档 1.txt

使用参考:

https://blog.csdn.net/weixin_38289699/article/details/78527919

 

 

 

3、postman工具, 可以模拟http及https的请求及响应。

但作为服务端的时候 生成的mock服务地址实在postman的服务器上的。服务的地址是个映射后的地址,和实际模拟的请求地址不一样。

 

使用方法参考地址:

https://blog.csdn.net/2301_80864686/article/details/135936366

 

 

https://geek-docs.com/postman/postman-tutorials/t_lib_115_postman_postman_mock_server.html

 

二、https 忽略证书验证的模拟请求及模拟服务代码样例。

 

 

 忽略证书验证是在客户端进行的操作,在服务端模拟服务的时候必须要有证书,没有证书没有证书开启不了https。

1、客户端样例:HttpsUtils.java

 

 

package com.xxx.util;

 

import org.slf4j.LoggerFactory;

 

import javax.net.ssl.HttpsURLConnection;

import javax.net.ssl.SSLContext;

import javax.net.ssl.TrustManager;

import javax.net.ssl.X509TrustManager;

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStreamReader;

import java.io.PrintWriter;

import java.net.*;

import java.security.KeyManagementException;

import java.security.NoSuchAlgorithmException;

import java.security.cert.X509Certificate;

import java.util.HashMap;

import java.util.Map;

 

 

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

/**

 * @author luohao  2024/05/11   htts请求工具类忽律ssl证书

 */

public class HttpsUtils {

   // private static final Logger logger = LogManager.getLogger(HttpsUtils.class);

    private static Logger logger = LoggerFactory.getLogger(FileUtil.class);

    //调用该类直接跳过ssl证书

    static {

        try {

            trustAllHttpsCertificates();

            HttpsURLConnection.setDefaultHostnameVerifier

                    (

                            (urlHostName, session) -> true

                    );

        } catch (Exception e) {

            logger.info("trustAllHttpsCertificates Exception");

        }

    }

 

    public static void main(String[] args) {

        String param = "[{\n" +

                "\t\"id\": \"1046000000000549\",\n" +

                "\t\"curtime\": \"2023-11-01 08:34:05\",\n" +

                "\t\"status\": \"2\"\n" +

                "}]";

     String ipPort=   "http://localhost:10002";

     

     String method= "/alarmFiled";

     

     String url=ipPort+method;

       // Map<String, Object> stringObjectMap = sendPostWithStatus("https://localhost:10002/alarmFiled", param);

     //  Map<String, Object> stringObjectMap = sendPostWithStatus("https://172.27.236.38:8000/test", param);

    //   Map<String, Object> stringObjectMap = sendPostWithStatus("https://www.baidu.com/?tn=62095104_27_oem_dg&ch=1", param);

    

     //调postman 模拟接口调不通  调百度网页等https的方法及模拟启动的 http及https的方法都可以调通

     Map<String, Object> stringObjectMap = sendPostWithStatus("https://a4e2bf89-6448-42aa-87e1-11fc1e442fc6.mock.pstmn.io", param);

 //   Map<String, Object> stringObjectMap = sendPostWithStatus(url, param);

        System.out.println(stringObjectMap.toString());

 

    }

    /**

     * 向指定 URL 发送POST方法的请求

     *

     * @param url   发送请求的 URL

     * @param param 请求参数

     * @return 所代表远程资源的响应结果

     */

    public static Map<String, Object> sendPostWithStatus(String url, String param) {

        Map<String, Object> map = new HashMap<>();

        PrintWriter out = null;

        String status = null;

        BufferedReader in = null;

        StringBuilder result = new StringBuilder();

        try {

            logger.info("sendPost - {}", url);

            URL realUrl = new URL(url);

 

            // 打开连接

            HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();

            // 默认是 GET方式

          //  conn.setRequestMethod("POST");

            conn.setRequestMethod("GET");

            // 设置是否向connection输出,因为这个是post请求,参数要放在http正文内,因此需要设为true

            conn.setDoOutput(true);

            conn.setDoInput(true);

            // Post 请求不能使用缓存

            conn.setUseCaches(false);

            conn.setInstanceFollowRedirects(true);

            // 配置本次连接的Content-type,参数类型为json

            conn.setRequestProperty("Content-Type", "application/json");

            // 通用请求头信息

            conn.setRequestProperty("accept", "*/*");

            conn.setRequestProperty("connection", "Keep-Alive");

            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

            conn.setRequestProperty("Accept-Charset", "utf-8");

            conn.setRequestProperty("contentType", "utf-8");

        //    conn.connect();

            out = new PrintWriter(conn.getOutputStream());

            //请求参数

  //          out.print(param);

            out.flush();

            //获取响应的状态码 请求成功为200

            status = Integer.toString(((HttpURLConnection) conn).getResponseCode());

            in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));

            String line;

            //获取响应内容

            while ((line = in.readLine()) != null) {

                result.append(line);

            }

            logger.info("recieve:{}", result);

        } catch (ConnectException e) {

            logger.error("HttpUtils.sendPostWithStatus ConnectException, url={}, param={}", url, param, e);

        } catch (SocketTimeoutException e) {

            logger.error("HttpUtils.sendPostWithStatus SocketTimeoutException, url={}, param={}", url, param, e);

        } catch (IOException e) {

            logger.error("HttpUtils.sendPostWithStatus IOException, url={}, param={}", url, param, e);

        } catch (Exception e) {

            logger.error("HttpsUtil.sendPostWithStatus Exception, url={}, param={}", url, param, e);

        } finally {

            try {

                if (out != null) {

                    out.close();

                }

                if (in != null) {

                    in.close();

                }

            } catch (IOException ex) {

                logger.error("in.close Exception, url={}, param={}", url, param, ex);

            }

        }

        map.put("status", status);

        map.put("result", result);

        return map;

    }

 

    /**

     * 跳过ssl证书

     */

    private static void trustAllHttpsCertificates()

            throws NoSuchAlgorithmException, KeyManagementException {

        TrustManager[] trustAllCerts = new TrustManager[1];

        trustAllCerts[0] = (TrustManager) new TrustAllManager();

        SSLContext sc = SSLContext.getInstance("SSL");

        sc.init(null, trustAllCerts, null);

        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

    }

 

    private static class TrustAllManager implements X509TrustManager {

        public X509Certificate[] getAcceptedIssuers() {

            return null;

        }

        public void checkServerTrusted(X509Certificate[] certs, String authType) {

        }

        public void checkClientTrusted(X509Certificate[] certs, String authType) {

        }

    }

}

 

 

 

1、服务端样例:HttpsUtils.java

package com.nrxt.dsmp.infocollect.main;

 

 

import java.io.*;

import java.net.*;

import java.lang.*;

 

import com.sun.net.httpserver.HttpsServer;

import java.security.KeyStore;

import javax.net.ssl.KeyManagerFactory;

import javax.net.ssl.TrustManagerFactory;

import com.sun.net.httpserver.*;

import javax.net.ssl.SSLEngine;

import javax.net.ssl.SSLParameters;

 

import java.io.InputStreamReader;

import java.io.Reader;

 

import javax.net.ssl.HostnameVerifier;

import javax.net.ssl.HttpsURLConnection;

import javax.net.ssl.SSLContext;

import javax.net.ssl.SSLSession;

import javax.net.ssl.TrustManager;

import javax.net.ssl.X509TrustManager;

import java.security.cert.X509Certificate;

 

import com.sun.net.httpserver.HttpExchange;

import com.sun.net.httpserver.HttpHandler;

import com.sun.net.httpserver.HttpServer;

import com.sun.net.httpserver.HttpsExchange;

 

public class SimpleHTTPSServer {

    public static class MyHandler implements HttpHandler {

        @Override

        public void handle(HttpExchange httpExchange) throws IOException {

            URI requestURI = httpExchange.getRequestURI();

            String URL = requestURI.getPath();

            System.out.println(URL);

            InputStream in = httpExchange.getRequestBody(); //获得输入流

            BufferedReader reader = new BufferedReader(new InputStreamReader(in));

            String temp;

            StringBuffer resBuffer = new StringBuffer();

            while ((temp = reader.readLine()) != null) {

                //logger.info("client request:" + temp);

                resBuffer.append(temp);

            }

            System.out.println(resBuffer);

            String response = "This is the response";

            HttpsExchange httpsExchange = (HttpsExchange) httpExchange;

            httpExchange.getResponseHeaders().add("Access-Control-Allow-Origin", "*");

            httpExchange.sendResponseHeaders(200, response.getBytes().length);

            OutputStream os = httpExchange.getResponseBody();

            os.write(response.getBytes());

            os.close();

 

 

        }

    }

 

    /**

     * @param args

     */

    public static void main(String[] args) throws Exception {

 

        try {

            // setup the socket address

            InetSocketAddress address = new InetSocketAddress("0.0.0.0",8000);

 

            // initialise the HTTPS server

            HttpsServer httpsServer = HttpsServer.create(address, 0);

            //TLS

            SSLContext sslContext = SSLContext.getInstance("SSL");

 

            // initialise the keystore

            char[] password = "666666".toCharArray();

            KeyStore ks = KeyStore.getInstance("JKS");

         //   FileInputStream fis = new FileInputStream("C:\\Program Files\\Java\\jdk1.8.0_211\\bin\\testkey.jks");

            FileInputStream fis = new FileInputStream("C:\\Program Files\\Java\\jdk1.8.0_121\\bin\\keystore.jks");

            ks.load(fis, password);

 

            // setup the key manager factory

            KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");

            kmf.init(ks, password);

 

            // setup the trust manager factory

            TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");

            tmf.init(ks);

 

            // setup the HTTPS context and parameters

            sslContext.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);

            httpsServer.setHttpsConfigurator(new HttpsConfigurator(sslContext) {

                public void configure(HttpsParameters params) {

                    try {

                        // initialise the SSL context

                        SSLContext context = getSSLContext();

                        SSLEngine engine = context.createSSLEngine();

                        params.setNeedClientAuth(false);

                        params.setCipherSuites(engine.getEnabledCipherSuites());

                        params.setProtocols(engine.getEnabledProtocols());

 

                        // Set the SSL parameters

                        SSLParameters sslParameters = context.getSupportedSSLParameters();

                        params.setSSLParameters(sslParameters);

 

                    } catch (Exception ex) {

                        System.out.println("Failed to create HTTPS port");

                    }

                }

            });

            httpsServer.createContext("/test", new MyHandler());

            httpsServer.setExecutor(null);

            httpsServer.start();

            System.out.println("开启成功");

        } catch (Exception exception) {

            System.out.println("Failed to create HTTPS server on port " + 8000 + " of localhost");

            exception.printStackTrace();

 

        }

    }

}

 

 

 

模拟服务端需要在 java home的安装目录bin目录下 生成证书 ,要使用管理员身份运行cmd及逆行生成。

 

 

1、右键桌面左下角的 Windows 图标,找到 Windows PowerShell(管理员) 点金进入。

 

2、切换到java home的安装目录bin目录下:

 C:\Program Files\Java\jdk1.8.0_121\bin>

 

3、执行命令

keytool -genkeypair -alias mykey -keyalg RSA -keysize 2048 -keystore keystore.jks

 

要记得输入的 密钥口令,并替换到上面的 模拟服务样例中,其他选项任意填写继续执行。

 char[] password = "666666".toCharArray();

 

 

4、最后会在 C:\Program Files\Java\jdk1.8.0_121\bin>

 目录下生成 keystore.jks文件,  替换上面样例中的 证书路径,

 FileInputStream fis = new FileInputStream("C:\\Program Files\\Java\\jdk1.8.0_121\\bin\\keystore.jks");

 

 

 

最后启动服务,并使用restclient-1.2.jar 工具,或则模拟测试样例进行测试即可。

 

模拟测试样例调百度网页等https的方法及模拟启动的 http及https的方法都可以调通,postman 模拟接口调不通 (待继续研究)。

 

测试样例中 POST或GET方法可以自己根据需要改变,conn.connect();这句要不要都能调用成功。

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

posted on 2024-05-13 19:01  luckyna  阅读(69)  评论(0编辑  收藏  举报

导航