HTTPClient基本使用
Posted starstarstar
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了HTTPClient基本使用相关的知识,希望对你有一定的参考价值。
使用maven,在xml中引用
<!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpclient --> <dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.2</version> </dependency>
第一个demo
第一个.java文件
package com.httpclient.demo; import org.apache.http.HttpEntity; 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.HttpClientBuilder; import org.apache.http.util.EntityUtils; import org.testng.annotations.Test; import java.io.IOException; public class HttpClientDemo @Test public void test01() //创建get请求 String uri = "https://www.baidu.com"; HttpGet get = new HttpGet(uri); //获取http客户端 CloseableHttpClient client = HttpClientBuilder.create().build(); //响应模型 CloseableHttpResponse response = null; try //由http客户端,发送get请求 response = client.execute(get); //从响应中,获取响应实体 HttpEntity respEntity = response.getEntity(); String result = EntityUtils.toString(respEntity, "utf-8"); System.out.println(result); catch (IOException e) e.printStackTrace();
执行结果:
以上是关于HTTPClient基本使用的主要内容,如果未能解决你的问题,请参考以下文章