HttpClient快速入门(一)

导入maven依赖

	<properties>
		<project.build.sourceEncoding>UTF-8project.build.sourceEncoding>
		<httpclient.version>4.5.9httpclient.version>
	properties>

	<dependencies>
		<dependency>
			<groupId>org.apache.httpcomponentsgroupId>
			<artifactId>httpclientartifactId>
			<version>${httpclient.version}version>
		dependency>
		<dependency>
			<groupId>org.apache.httpcomponentsgroupId>
			<artifactId>httpclient-cacheartifactId>
			<version>${httpclient.version}version>
		dependency>
		<dependency>
			<groupId>org.apache.httpcomponentsgroupId>
			<artifactId>httpmimeartifactId>
			<version>${httpclient.version}version>
		dependency>
		<dependency>
			<groupId>org.apache.httpcomponentsgroupId>
			<artifactId>fluent-hcartifactId>
			<version>${httpclient.version}version>
		dependency>
		<dependency>
			<groupId>junitgroupId>
			<artifactId>junitartifactId>
			<version>3.8.1version>
			<scope>testscope>
		dependency>
	dependencies>

http get请求

基本例子

public class QuickStartTest {
	@Test
	public void getTest() throws Exception {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpGet httpGet = new HttpGet("http://www.xinhuanet.com/politics/");
		CloseableHttpResponse response = httpclient.execute(httpGet);
		try {
		    Assert.assertEquals("HTTP/1.1 200 OK", response.getStatusLine().toString());
		    HttpEntity entity = response.getEntity();
		    // 确保响应头完成响应
		    EntityUtils.consume(entity);
		} finally {
		    response.close();
		}
	}
}

测试通过
在这里插入图片描述

响应对象保留底层HTTP连接,允许响应内容直接从网络套接(socket)字流式传输。为了确保正确释放系统资源,用户必须从finally子句调用CloseableHttpResponse.close()方法。 请注意,如果未完全使用响应内容,则无法安全地重复使用基础连接,连接管理器将关闭并放弃该基础连接。

http post带参数请求

这里我自己搭建一个post请求的api,请忽略,无影响,服务端代码如下

@Path("hello")
@Component
public class DemoResource {
	Logger logger = LoggerFactory.getLogger("DemoResource");
	
    @POST
    @Path("quartstart")
    public Response doHttpclient(String param) {
		logger.error("参数:{}", param);
        return Response.ok().build();
    }
    
}

基本例子

public class QuickStartTest {
	@Test
	public void postTest() throws Exception {
		HttpPost httpPost = new HttpPost("http://localhost:8080/jersey-spring-webapp/v0/hello/quartstart");
		List <NameValuePair> nvps = new ArrayList <NameValuePair>();
		nvps.add(new BasicNameValuePair("username", "vip"));
		nvps.add(new BasicNameValuePair("password", "secret"));
		httpPost.setEntity(new UrlEncodedFormEntity(nvps));
		CloseableHttpClient httpclient = HttpClients.createDefault();
		CloseableHttpResponse response = httpclient.execute(httpPost);

		try {
		    Assert.assertEquals("HTTP/1.1 200 OK", response.getStatusLine().toString());
		    HttpEntity entity2 = response.getEntity();
		    // 确保响应头完成响应
		    EntityUtils.consume(entity2);
		} finally {
		    response.close();
		}
	}
}

httpclient测试通过
在这里插入图片描述
服务端对应输出日志

在这里插入图片描述

流式api

调用方式上采用fluent api,基本例子如下

public class FluentQuickStart {

	public static void main(String[] args) throws Exception {
		Content content = Request.Get("http://www.xinhuanet.com/politics/").execute().returnContent();
		ContentType type = content.getType();
		System.out.println(type);
		Content content2 = Request.Post("http://localhost:8080/jersey-spring-webapp/v0/hello/quartstart")
				.bodyForm(Form.form().add("username", "vip").add("password", "secret").build()).execute().returnContent();
		ContentType type2 = content2.getType();
		System.out.println(type2);
	}

}

测试结果

text/html
text/plain; charset=ISO-8859-1

参考教程:官网教程入口
后续将参考官网httpclient-tutorial.pdf学习:对应文档链接:https://pan.baidu.com/s/1cHn9sZn22friAP5W5AZGZg
提取码:r5ut

你可能感兴趣的:(httpclient)