基于HttpClient的Http接口测试用例

1. 通过Request

		//创建可关闭的httpclient实例
		CloseableHttpClient httpclient = HttpClients.createDefault();
		//HTTP请求
		HttpUriRequest request = new HttpGet("http://localhost:8080/");
		// 打印请求信息
        System.out.println(request.getRequestLine());
        try {
            // 发送请求,返回响应
            HttpResponse response = httpclient.execute(request); 
            // 打印响应信息
            System.out.println(response.getStatusLine());
        } catch (ClientProtocolException e) {
            // 协议错误
            e.printStackTrace();
        } catch (IOException e) {
            // 网络异常
            e.printStackTrace();
        }

2. 通过HttpGet

		//创建默认的httpclient实例
		CloseableHttpClient httpclient = HttpClients.createDefault();
		//创建HttpGet
		HttpGet httpget = new HttpGet("http://localhost:8080/");
		System.out.println("executing request" +" " + httpget.getURI());
		try {
			//执行get请求
			HttpResponse response = httpclient.execute(httpget);
			//获取响应实体
			HttpEntity entity = response.getEntity();
			System.out.println("------------------------------------------------");
			//打印响应状态
			System.out.println(response.getStatusLine());
			if (entity != null){
				//打印响应内容长度
				System.out.println("response content length:" + entity.getContentLength());
				//打印响应内容
				System.out.println("Response Content"+ EntityUtils.toString(entity));
				System.out.println("--------------------------------------------");
			}
		} finally {
			//关闭连接,释放资源
			httpget.releaseConnection();

		}



 

你可能感兴趣的:(HttpClient,接口测试)