简单使用HttpClient

HttpClient版本



	org.apache.httpcomponents
	httpclient
	4.3.5

使用方法步骤

get请求

第一步:把HttpClient使用的jar包添加到工程中。

第二步:创建一个HttpClient的测试类

第三步:创建测试方法。

第四步:创建一个HttpClient对象

第五步:创建一个HttpGet对象,需要制定一个请求的url

第六步:执行请求。

第七步:接收返回结果。HttpEntity对象。

第八步:取响应的内容。

第九步:关闭HttpGet、HttpClient。

测试代码

@Test
public void testHttpGet() throws ClientProtocolException, IOException {
	// 把HttpClient使用的jar包添加到工程中。
	// 创建一个HttpClient的测试类
	// 创建测试方法。
		
	// 创建一个HttpClient对象
	CloseableHttpClient httpClient = HttpClients.createDefault();
		
	// 创建一个HttpGet对象,需要制定一个请求的url
	HttpGet httpGet = new HttpGet("http://www.itmayiedu.com");
		
	// 执行请求,获得response
	CloseableHttpResponse response = httpClient.execute(httpGet);
		
	// 接收返回结果。转换成HttpEntity对象。
	HttpEntity httpEntity = response.getEntity();
		
	// 使用EntityUtils类toString()取响应的内容
	String string = EntityUtils.toString(httpEntity);
	System.out.println(string);
		
	// 关闭Closeable的对象,response和httpClient
	response.close();
	httpClient.close();
}

结果












蚂蚁课堂-中国专业的IT职业在线教育平台

























省略body部分

post请求

第一步:创建一个httpClient对象

第二步:创建一个HttpPost对象。需要指定一个url

第三步:创建一个list模拟表单,list中每个元素是一个NameValuePair对象

第四步:需要把表单包装到Entity对象中。StringEntity

第五步:执行请求。

第六步:接收返回结果

第七步:关闭流。

测试代码

controller

@ResponseBody
@RequestMapping(value="/testpost", method=RequestMethod.POST)
public String testPost(String name, String pass) {
	System.out.println(name);
	System.out.println(pass);
	return "ok";
}

Test

@Test
public void testHttpPost() throws ClientProtocolException, IOException {
	// 创建一个httpClient对象
	CloseableHttpClient httpClient = HttpClients.createDefault();
		
	// 创建一个HttpPost对象。需要指定一个url(url带.html是因为在web.xml中springmvc前端控制器配置了伪静态url拦截
	HttpPost httpPost = new HttpPost("http://localhost:8082/testpost.html");
		
	// 创建一个list模拟表单传入的参数,list中每个元素是一个NameValuePair对象
	List formList = new ArrayList<>();
	formList.add(new BasicNameValuePair("name", "张三"));
	formList.add(new BasicNameValuePair("pass", "123456"));
		
	// 需要把表单包装到Entity对象中。StringEntity
	StringEntity entity = new UrlEncodedFormEntity(formList, "utf-8");
	httpPost.setEntity(entity);

	// 执行请求
	CloseableHttpResponse response = httpClient.execute(httpPost);
		
	// 接收返回结果
	HttpEntity httpEntity = response.getEntity();
	String string = EntityUtils.toString(httpEntity);
	System.out.println(string);
		
	// 关闭流
	response.close();
	httpClient.close();
}

结果

请求返回了OK,打印出了请求参数.



你可能感兴趣的:(HttpClient)