秒懂HTTPS接口(接口測試篇)

前言

下面我們來測試下我們秒懂HTTPS接口(實現篇)寫的HTTPS接口(Java版)

技術選型:

  • HTTP工具包:HttpClient 4.5.5
  • 測試框架:TestNG
  • Json序列化庫:fastjson

具體實現

引包

引入相關包

<!--引入接口測試相關包-->
        <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>

測試HTTPS接口可以通過以下兩種方式:

  • 採用繞過證書驗證實現HTTPS
  • 採用設置信任自簽名證書實現HTTPS

採用繞過證書驗證測試HTTPS接口

src/test/util下創建HttpUtil工具類

實現繞過SSL驗證方法

/**
	 * 繞過SSL驗證
	 *
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws KeyManagementException
	 */
	public static SSLContext createIgnoreVerifySSL() throws NoSuchAlgorithmException, KeyManagementException {
		SSLContext sslContext = SSLContext.getInstance("SSLv3");

		// 實現一個X509TrustManager接口,用於繞過驗證,不用修改裏面的方法
		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;
	}

實現繞過SSL證書,發送Get請求方法

/**
	 * 繞過SSL證書,發送Get請求
	 * @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 {
		//採用繞過驗證的方式處理https請求
		SSLContext sslContext = createIgnoreVerifySSL();
		final SSLConnectionSocketFactory sslsf;

		//設置協議http和https對應的處理socket鏈接工廠的對象
		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);

		//創建自定義的httpclient對象
		CloseableHttpClient httpClient = HttpClients.custom()
				.setSSLSocketFactory(sslsf)
				.setConnectionManager(cm)
				.build();

		String result = null;
		//裝填參數
		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;
		}
		//創建get方式請求對象
		HttpGet httpGet = new HttpGet(url);
		//執行請求操作,並拿到結果(同步阻塞)
		CloseableHttpResponse response = httpClient.execute(httpGet);
		if (response.getStatusLine().getStatusCode() == 200){
			//獲取結果實體
			HttpEntity httpEntity = response.getEntity();
			//按指定編碼轉換結果實體爲String類型
			result = EntityUtils.toString(httpEntity,"UTF-8");
		}

		//釋放鏈接
		response.close();

		return result;
	}

實現繞過SSL證書,發送Post請求(Json形式)方法

/**
	 * 繞過SSL證書,發送Post請求(Json形式)
	 * @param url
	 * @param param
	 * @return
	 * @throws IOException
	 * @throws KeyManagementException
	 * @throws NoSuchAlgorithmException
	 */
	public static String doIgnoreVerifySSLPost(String url, JSONObject param)
			throws IOException, KeyManagementException, NoSuchAlgorithmException {
		//採用繞過驗證的方式處理https請求
		SSLContext sslContext = createIgnoreVerifySSL();
		final SSLConnectionSocketFactory sslsf;

		//設置協議http和https對應的處理socket鏈接工廠的對象
		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);

		//創建自定義的httpclient對象
		CloseableHttpClient httpClient = HttpClients.custom()
				.setSSLSocketFactory(sslsf)
				.setConnectionManager(cm)
				.build();

		String result = null;
		//創建post方式請求對象
		HttpPost httpPost = new HttpPost(url);
		//裝填參數
		StringEntity entity = new StringEntity(param.toString(),"utf-8");
		entity.setContentEncoding("UTF-8");
		entity.setContentType("application/json");
		//設置參數到請求對象中
		httpPost.setEntity(entity);

		//執行請求操作,並拿到結果(同步阻塞)
		CloseableHttpResponse response = httpClient.execute(httpPost);
		if (response.getStatusLine().getStatusCode() == 200){
			//獲取結果實體
			HttpEntity httpEntity = response.getEntity();
			//按指定編碼轉換結果實體爲String類型
			result = EntityUtils.toString(httpEntity,"UTF-8");
		}

		//釋放鏈接
		response.close();

		return result;
	}

src/test/cases下創建HttpTest測試類
實現測試方法

@Test(enabled = true,description = "測試繞過SSL證書Post方法")
	public void doIgnoreVerifySSLPostTest() throws IOException, NoSuchAlgorithmException, KeyManagementException {
		String url = "https://localhost/springboot/person";
		//裝填參數
		JSONObject param = new JSONObject();
		param.put("name","doIgnoreVerifySSLPost");
		param.put("age",20);
		//調用方法
		String response = HttpUtil.doIgnoreVerifySSLPost(url,param);
		//斷言返回結果是否爲空
		Assert.assertNotNull(response);
		System.out.println("【doIgnoreVerifySSLPost】"+response);
	}

	@Test(enabled = true,description = "測試繞過SSL證書Get方法")
	public void doIgnoreVerifySSLGetTest() throws IOException, NoSuchAlgorithmException, KeyManagementException {
		String url = "https://localhost/springboot/person";
		//調用方法
		String response = HttpUtil.doIgnoreVerifySSLGet(url,null);
		//斷言返回結果是否爲空
		Assert.assertNotNull(response);
		System.out.println("【doIgnoreVerifySSLGet】"+response);
	}

運行測試結果
在這裏插入圖片描述

採用設置信任自簽名證書測試HTTPS接口

在HttpUtil工具類實現驗證SSL證書,發送Get請求方法

/**
	 * 驗證SSL證書,發送Get請求
	 * @param url
	 * @param params
	 * @return
	 * @throws IOException
	 */
	public static String doVerifySSLGet(String url, Map<String,Object> params) throws IOException {
		//採用驗證的SSL證書方式處理https請求
		SSLContext sslContext = SSLCustom("./src/main/resources/keystore.p12","zuozewei");
		final SSLConnectionSocketFactory sslsf;

		// 設置協議http和https對應的處理socket鏈接工廠的對象
		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);

		//創建自定義的httpclient對象
		CloseableHttpClient httpClient = HttpClients.custom()
				.setSSLSocketFactory(sslsf)
				.setConnectionManager(cm)
				.build();

		String result = null;
		//裝填參數
		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;
		}

		//創建get方式請求對象
		HttpGet httpGet = new HttpGet(url);
		//執行請求操作,並拿到結果(同步阻塞)
		CloseableHttpResponse response = httpClient.execute(httpGet);
		if (response.getStatusLine().getStatusCode() == 200){
			//獲取結果實體
			HttpEntity httpEntity = response.getEntity();
			//按指定編碼轉換結果實體爲String類型
			result = EntityUtils.toString(httpEntity,"UTF-8");
		}

		//釋放鏈接
		response.close();

		return result;
	}

實現驗證SSL證書,發送Post請求(Json形式)方法

/**
	 * 驗證SSL證書,發送Post請求(Json形式)
	 * @param url
	 * @param param
	 * @return
	 * @throws IOException
	 */
	public static String doVerifySSLPost(String url, JSONObject param) throws IOException {
		//採用驗證的SSL證書方式處理https請求
		SSLContext sslContext = SSLCustom("./src/main/resources/keystore.p12","zuozewei");
		final SSLConnectionSocketFactory sslsf;

		//設置協議http和https對應的處理socket鏈接工廠的對象
		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);

		//創建自定義的httpclient對象
		CloseableHttpClient httpClient = HttpClients.custom()
				.setSSLSocketFactory(sslsf)
				.setConnectionManager(cm)
				.build();

		String result = null;

		//創建post方式請求對象
		HttpPost httpPost = new HttpPost(url);
		//裝填參數
		StringEntity entity = new StringEntity(param.toString(),"utf-8");
		entity.setContentEncoding("UTF-8");
		entity.setContentType("application/json");
		//設置參數到請求對象中
		httpPost.setEntity(entity);
		//執行請求操作,並拿到結果(同步阻塞)
		CloseableHttpResponse response = httpClient.execute(httpPost);
		if (response.getStatusLine().getStatusCode() == 200){
			//獲取結果實體
			HttpEntity httpEntity = response.getEntity();
			//按指定編碼轉換結果實體爲String類型
			result = EntityUtils.toString(httpEntity,"UTF-8");
		}
		//釋放鏈接
		response.close();

		return result;
	}

在HttpTest測試類,實現測試方法

@Test(enabled = true,description = "測試驗證SSL證書Post方法")
	public void doVerifySSLPostTest() throws IOException {
		String url = "https://localhost/springboot/person";
		//裝填參數
		JSONObject param = new JSONObject();
		param.put("name","doVerifySSLPost");
		param.put("age",20);
		//調用方法
		String response = HttpUtil.doVerifySSLPost(url,param);
		//斷言返回結果是否爲空
		Assert.assertNotNull(response);
		System.out.println("【doVerifySSLPost】"+response);
	}

	@Test(enabled = true,description = "測試驗證SSL證書Get方法")
	public void doVerifySSLGetTest() throws IOException {
		String url = "https://localhost/springboot/person";
		//調用方法
		String response = HttpUtil.doVerifySSLGet(url,null);
		//斷言返回結果是否爲空
		Assert.assertNotNull(response);
		System.out.println("【doVerifySSLGet】"+response);
	}

運行測試結果
在這裏插入圖片描述

驗證數據庫

查詢數據庫結果
在這裏插入圖片描述

完整項目結構

在這裏插入圖片描述

秒懂HTTPS接口系列源碼:
https://github.com/zuozewei/Springboot-https-demo

相關係列:
秒懂HTTPS接口(原理篇)
秒懂HTTPS接口(實現篇)
秒懂HTTPS接口(JMeter壓測篇)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章