“This is my 26th day of participating in the First Wen Challenge 2022.First challenge in 2022”

One, foreword

Now let’s test our second understand HTTPS interface (implementation) write HTTPS interface (Java version)

Technical selection:

  • HTTP tool package: HttpClient 4.5.5
  • Test framework: TestNG
  • Json serialization library: FastJSON

Second, concrete implementation

1, led package

Importing related packages

<! Interface test package -->
        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.5.5</version>
        </dependency>
        <dependency>
            <groupId>org.testng</groupId>
            <artifactId>testng</artifactId>
            <version>6.14.3</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
Copy the code

You can test the HTTPS interface in either of the following ways:

  • HTTPS is implemented by bypassing certificate authentication
  • HTTPS is implemented by setting the trusted self-signed certificate

2. Bypass certificate authentication to test HTTPS interfaces

Create the HttpUtil utility class under SRC /test/util

Implement bypass SSL authentication method

/** * Bypass SSL authentication **@return
	 * @throws NoSuchAlgorithmException
	 * @throws KeyManagementException
	 */
	public static SSLContext createIgnoreVerifySSL(a) throws NoSuchAlgorithmException, KeyManagementException {
		SSLContext sslContext = SSLContext.getInstance("SSLv3");

		// Implement an X509TrustManager interface to bypass validation without modifying the methods inside
		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; }}; sslContext.init(null.new TrustManager[] { trustManager }, null);
		return sslContext;
	}
Copy the code

Realize bypass SSL certificate, send Get request method

/** * bypass SSL certificate, send Get request *@param url
	 * @param params
	 * @return
	 * @throws IOException
	 * @throws KeyManagementException
	 * @throws NoSuchAlgorithmException
	 */
	public static String doIgnoreVerifySSLGet(String url, Map<String,Object> params)
			throws IOException, KeyManagementException, NoSuchAlgorithmException {
		// Process HTTPS requests in a way that bypasses validation
		SSLContext sslContext = createIgnoreVerifySSL();
		final SSLConnectionSocketFactory sslsf;

		// Set the object corresponding to the protocol HTTP and HTTPS to handle the socket link factory
		sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
		final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
				.register("http".new PlainConnectionSocketFactory())
				.register("https", sslsf)
				.build();

		final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
		cm.setMaxTotal(100);

		// Create a custom HttpClient object
		CloseableHttpClient httpClient = HttpClients.custom()
				.setSSLSocketFactory(sslsf)
				.setConnectionManager(cm)
				.build();

		String result = null;
		// Loading parameters
		StringBuffer param = new StringBuffer();
		if(params ! =null && !params.isEmpty()) {
			int i = 0;
			for (String key : params.keySet()) {
				if (i == 0) {
					param.append("?");
				} else {
					param.append("&");
				}
				param.append(key).append("=").append(params.get(key));
				i++;
			}
			url += param;
		}
		// Create a get request object
		HttpGet httpGet = new HttpGet(url);
		// Execute the request and get the result (synchronous block)
		CloseableHttpResponse response = httpClient.execute(httpGet);
		if (response.getStatusLine().getStatusCode() == 200) {// Get the result entity
			HttpEntity httpEntity = response.getEntity();
			// Convert the resulting entity to String with the specified encoding
			result = EntityUtils.toString(httpEntity,"UTF-8");
		}

		// Release the link
		response.close();

		return result;
	}
Copy the code

Implement bypass SSL certificate, send Post request (Json form) method

/** * Bypass SSL certificate, send Post request (Json form) *@param url
	 * @param param
	 * @return
	 * @throws IOException
	 * @throws KeyManagementException
	 * @throws NoSuchAlgorithmException
	 */
	public static String doIgnoreVerifySSLPost(String url, JSONObject param)
			throws IOException, KeyManagementException, NoSuchAlgorithmException {
		// Process HTTPS requests in a way that bypasses validation
		SSLContext sslContext = createIgnoreVerifySSL();
		final SSLConnectionSocketFactory sslsf;

		// Set the object corresponding to the protocol HTTP and HTTPS to handle the socket link factory
		sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
		final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
				.register("http".new PlainConnectionSocketFactory())
				.register("https", sslsf)
				.build();

		final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
		cm.setMaxTotal(100);

		// Create a custom HttpClient object
		CloseableHttpClient httpClient = HttpClients.custom()
				.setSSLSocketFactory(sslsf)
				.setConnectionManager(cm)
				.build();

		String result = null;
		// Create a POST request object
		HttpPost httpPost = new HttpPost(url);
		// Loading parameters
		StringEntity entity = new StringEntity(param.toString(),"utf-8");
		entity.setContentEncoding("UTF-8");
		entity.setContentType("application/json");
		// Set parameters to the request object
		httpPost.setEntity(entity);

		// Execute the request and get the result (synchronous block)
		CloseableHttpResponse response = httpClient.execute(httpPost);
		if (response.getStatusLine().getStatusCode() == 200) {// Get the result entity
			HttpEntity httpEntity = response.getEntity();
			// Convert the resulting entity to String with the specified encoding
			result = EntityUtils.toString(httpEntity,"UTF-8");
		}

		// Release the link
		response.close();

		return result;
	}
Copy the code

Create the HttpTest test class under SRC /test/cases to implement the test method

@test (enabled = true,description = "Test bypass SSL certificate Post method ")
	public void doIgnoreVerifySSLPostTest(a) throws IOException, NoSuchAlgorithmException, KeyManagementException {
		String url = "https://localhost/springboot/person";
		// Loading parameters
		JSONObject param = new JSONObject();
		param.put("name"."doIgnoreVerifySSLPost");
		param.put("age".20);
		// Call the method
		String response = HttpUtil.doIgnoreVerifySSLPost(url,param);
		// Assert whether the return result is null
		Assert.assertNotNull(response);
		System.out.println("DoIgnoreVerifySSLPost"+response);
	}

	@test (enabled = true,description = "Test bypass SSL certificate Get method ")
	public void doIgnoreVerifySSLGetTest(a) throws IOException, NoSuchAlgorithmException, KeyManagementException {
		String url = "https://localhost/springboot/person";
		// Call the method
		String response = HttpUtil.doIgnoreVerifySSLGet(url,null);
		// Assert whether the return result is null
		Assert.assertNotNull(response);
		System.out.println("DoIgnoreVerifySSLGet"+response);
	}
Copy the code

Run test results

3. Use the trusted self-signed certificate to test the HTTPS interface

In the HttpUtil utility class implementation to verify SSL certificate, send Get request method

/** * Verify SSL certificate, send Get request *@param url
	 * @param params
	 * @return
	 * @throws IOException
	 */
	public static String doVerifySSLGet(String url, Map<String,Object> params) throws IOException {
		// Process HTTPS requests using authenticated SSL certificates
		SSLContext sslContext = SSLCustom("./src/main/resources/keystore.p12"."zuozewei");
		final SSLConnectionSocketFactory sslsf;

		// Set the object corresponding to the protocol HTTP and HTTPS to handle the socket link factory
		sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
		final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
				.register("http".new PlainConnectionSocketFactory())
				.register("https", sslsf)
				.build();

		final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
		cm.setMaxTotal(100);

		// Create a custom HttpClient object
		CloseableHttpClient httpClient = HttpClients.custom()
				.setSSLSocketFactory(sslsf)
				.setConnectionManager(cm)
				.build();

		String result = null;
		// Loading parameters
		StringBuffer param = new StringBuffer();
		if(params ! =null && !params.isEmpty()) {
			int i = 0;
			for (String key : params.keySet()) {
				if (i == 0) {
					param.append("?");
				} else {
					param.append("&");
				}
				param.append(key).append("=").append(params.get(key));
				i++;
			}
			url += param;
		}

		// Create a get request object
		HttpGet httpGet = new HttpGet(url);
		// Execute the request and get the result (synchronous block)
		CloseableHttpResponse response = httpClient.execute(httpGet);
		if (response.getStatusLine().getStatusCode() == 200) {// Get the result entity
			HttpEntity httpEntity = response.getEntity();
			// Convert the resulting entity to String with the specified encoding
			result = EntityUtils.toString(httpEntity,"UTF-8");
		}

		// Release the link
		response.close();

		return result;
	}
Copy the code

Implement SSL certificate verification, send Post request (Json form) method

/** * Verify SSL certificate, send Post request (Json form) *@param url
	 * @param param
	 * @return
	 * @throws IOException
	 */
	public static String doVerifySSLPost(String url, JSONObject param) throws IOException {
		// Process HTTPS requests using authenticated SSL certificates
		SSLContext sslContext = SSLCustom("./src/main/resources/keystore.p12"."zuozewei");
		final SSLConnectionSocketFactory sslsf;

		// Set the object corresponding to the protocol HTTP and HTTPS to handle the socket link factory
		sslsf = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
		final Registry<ConnectionSocketFactory> registry = RegistryBuilder.<ConnectionSocketFactory>create()
				.register("http".new PlainConnectionSocketFactory())
				.register("https", sslsf)
				.build();

		final PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(registry);
		cm.setMaxTotal(100);

		// Create a custom HttpClient object
		CloseableHttpClient httpClient = HttpClients.custom()
				.setSSLSocketFactory(sslsf)
				.setConnectionManager(cm)
				.build();

		String result = null;

		// Create a POST request object
		HttpPost httpPost = new HttpPost(url);
		// Loading parameters
		StringEntity entity = new StringEntity(param.toString(),"utf-8");
		entity.setContentEncoding("UTF-8");
		entity.setContentType("application/json");
		// Set parameters to the request object
		httpPost.setEntity(entity);
		// Execute the request and get the result (synchronous block)
		CloseableHttpResponse response = httpClient.execute(httpPost);
		if (response.getStatusLine().getStatusCode() == 200) {// Get the result entity
			HttpEntity httpEntity = response.getEntity();
			// Convert the resulting entity to String with the specified encoding
			result = EntityUtils.toString(httpEntity,"UTF-8");
		}
		// Release the link
		response.close();

		return result;
	}
Copy the code

The HttpTest test class implements the test method

@test (enabled = true,description = "Test SSL certificate Post method ")
	public void doVerifySSLPostTest(a) throws IOException {
		String url = "https://localhost/springboot/person";
		// Loading parameters
		JSONObject param = new JSONObject();
		param.put("name"."doVerifySSLPost");
		param.put("age".20);
		// Call the method
		String response = HttpUtil.doVerifySSLPost(url,param);
		// Assert whether the return result is null
		Assert.assertNotNull(response);
		System.out.println("[doVerifySSLPost]+response);
	}

	@test (enabled = true,description = "Test SSL certificate Get method ")
	public void doVerifySSLGetTest(a) throws IOException {
		String url = "https://localhost/springboot/person";
		// Call the method
		String response = HttpUtil.doVerifySSLGet(url,null);
		// Assert whether the return result is null
		Assert.assertNotNull(response);
		System.out.println("[doVerifySSLGet]+response);
	}
Copy the code

Run test results

4. Verify the database

Database Query result

Iii. Complete project structure

Second to understand HTTPS interface series source code:

  • Github.com/zuozewei/bl…