API自动化测试一(eclipse+maven+java+Httpclinet)

package com.test.client;


import java.io.IOException;
import java.util.HashMap;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;



public class TestGetApi {
	public static void main(String[] args) throws ClientProtocolException, IOException {
		
		//接口地址&登陆信息&参数
		String url = "";//被测的API地址
		
		//声明变量
		CloseableHttpClient httpclient;//实例化一个可以关闭流释放流相关资源的httpclient对象;抽象类不可直接实例化其本身
		HttpGet httpGet;
		CloseableHttpResponse httpResponse;
		HttpEntity responseBody;
		int responseCode;
		Header[] responseHeader;
		
		httpclient = HttpClients.createDefault();//创建httpclient实例,httpclient是一个传输库,用于在客户端发送和接受http消息
		httpGet = new HttpGet(url);//实例化请求post/get等诸多
		httpGet.addHeader("Cookie", "Cookie");//被测接口需要Cookie,才可以请求通
		httpResponse = httpclient.execute(httpGet);//httplient发送get类型的请求,执行成功,得到响应返回值
		
		responseCode = httpResponse.getStatusLine().getStatusCode();//获取返回值状态
		responseBody = httpResponse.getEntity();//获取返回值body
		responseHeader = httpResponse.getAllHeaders();//获取返回值header信息
		
		//因为返回的Entity看不懂,需要用工具类tostring一下,就是正常的body了。
		String responseBodyString = EntityUtils.toString(responseBody, "utf-8");
	    
		//header:[Lorg.apache.http.Header;@4a9789ee,所以使用hashmap将header信息以键值对形式展示出来,
	    HashMap<String, String> hashmap=new HashMap<String, String>();
	    for(Header header:responseHeader) {
	    	hashmap.put(header.getName(), header.getValue());
	    }
	    
		System.out.println(responseCode);
		System.out.println(responseBodyString);
		System.out.println(hashmap);
		
	}
}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值