Java語言搭建介面自動化框架學習一(單介面請求和響應)

愛學習的崽崽子發表於2020-11-22

maven專案:pom.xml匯入httpclient依賴

	<dependencies>
		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.6</version>
		</dependency>
	</dependencies>

模擬傳送get請求

		//1、設定以get請求方式請求url
		HttpGet get = new HttpGet("測試的介面地址");		
		//2、設定請求頭和入參(如有),模擬請求報文
		get.setHeader("請求頭欄位", "欄位值");
		//3、程式碼模擬傳送請求前要建立一個傳送請求的客戶端
		HttpClient httpClient = HttpClients.createDefault();	
		//4、傳送請求並獲取響應報文
		HttpResponse httpResponse = httpClient.execute(get);

響應報文獲取

		//5、響應報文格式化拆解:響應頭+響應體+響應狀態碼
		Header[] allHeaders = httpResponse.getAllHeaders();
		System.out.println("響應頭:"+Arrays.toString(allHeaders));
		HttpEntity httpEntity = httpResponse.getEntity();
		String body = EntityUtils.toString(httpEntity);
		System.out.println("響應體:"+body);		
		int statusCode = httpResponse.getStatusLine().getStatusCode();
		System.out.println("響應碼:"+statusCode);

模擬傳送post請求

        //和get請求基本一致,需要新增入參程式碼以及對應新增的響應頭設定,響應報文獲取和上面保持一致
        HttpPost post = new HttpPost("測試的介面地址");
        //請求頭根據需求文件對應新增,舉個例子如下設定
        post.setHeader("Content-Type", "application/json");
		String json = "複製入參json格式的請求報文";
		//把json入參放入請求中
		post.setEntity(new StringEntity(json,"utf-8"));
		
		HttpClient httpClient = HttpClients.createDefault();	
		HttpResponse httpResponse = httpClient.execute(post);

相關文章