HttpClient学习
1. 导入需要的pom文件
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.12</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastJson</artifactId>
<version>1.2.7</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.16</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.5</version>
</dependency>
</dependencies>
2.GET请求的测试
2.1 测试代码
package com.wcc;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
public class HttpGetTest {
@Test
public void getTest001(){
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpGet httpGet = new HttpGet("http://localhost:20000/getTest01");
CloseableHttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(httpGet);
HttpEntity entity = httpResponse.getEntity();
System.out.println("响应状态为"+httpResponse.getStatusLine());
if (entity!=null){
System.out.println("响应的内容长度为"+entity.getContentLength());
System.out.println("响应内容为"+ EntityUtils.toString(entity));
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void getTest002(){
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
StringBuffer sb =new StringBuffer();
sb.append("name=xiaoliu");
sb.append("&");
sb.append("age=18");
String url = "http://localhost:20000/getTest02?" + sb;
System.out.println("请求的地址为"+url);
HttpGet httpGet = new HttpGet(url);
RequestConfig requestConfig = RequestConfig.custom()
.setConnectionRequestTimeout(5000)
.setConnectTimeout(5000)
.setSocketTimeout(5000)
.setRedirectsEnabled(true)
.build();
httpGet.setConfig(requestConfig);
CloseableHttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(httpGet);
HttpEntity entity = httpResponse.getEntity();
System.out.println("请求的响应状态为"+httpResponse.getStatusLine());
if (entity != null){
System.out.println("响应的实体长度为"+entity.getContentLength());
System.out.println("响应的内容为"+EntityUtils.toString(entity));
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void getTest003(){
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
URI uri = null;
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("name","wang"));
params.add(new BasicNameValuePair("age","18"));
try {
uri = new URIBuilder().setScheme("http").setHost("localhost").setPort(20000)
.setPath("getTest02").setParameters(params).build();
HttpGet httpGet = new HttpGet(uri);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000)
.setConnectTimeout(5000).setConnectionRequestTimeout(5000).build();
httpGet.setConfig(requestConfig);
try {
CloseableHttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity entity = httpResponse.getEntity();
System.out.println("响应状态为"+httpResponse.getStatusLine());
if ( entity != null){
System.out.println("响应内容的长度为:"+entity.getContentLength());
System.out.println("响应内容为:"+EntityUtils.toString(entity));
}
} catch (IOException e) {
e.printStackTrace();
}
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
2.2 对应的控制层代码
@RestController
public class HttpClentGetTest {
@RequestMapping(value = "getTest01",method = RequestMethod.GET)
public String doGetTest01(){
return "123";
}
@RequestMapping(value = "getTest02",method = RequestMethod.GET)
public String doGetTest02(String name,int age){
return name +"已经"+age+"岁了";
}
}
3.POST请求
3.1 测试代码
package com.wcc;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.sun.org.apache.bcel.internal.generic.NEW;
import com.wcc.pojo.User;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.junit.jupiter.api.Test;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
public class HttpPostTest {
@Test
public void postTest01(){
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("http://localhost:20000/postTest001");
try {
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
System.out.println("响应的状态为:"+httpResponse.getStatusLine());
if (entity != null){
System.out.println("响应的内容长度:"+entity.getContentLength());
System.out.println("响应的内容为"+ EntityUtils.toString(entity));
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void postTest002(){
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
StringBuffer params = new StringBuffer();
params.append("name=xiaoliu").append("&").append("doing=昨晚腰疼");
HttpPost httpPost = new HttpPost("http://localhost:20000/postTest002?" + params);
try {
httpPost.setHeader("Content-Type","application/json;charset=utf-8");
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
System.out.println("响应状态为"+httpResponse.getStatusLine());
if ( entity!=null ){
System.out.println("响应内容长度为"+entity.getContentLength());
System.out.println("响应的内容为"+EntityUtils.toString(entity));
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void postTest003(){
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("name","小王"));
params.add(new BasicNameValuePair("doing","xuexi"));
try {
URI uri = new URIBuilder().setScheme("http").setHost("localhost").setPort(20000).setPath("postTest002")
.setParameters(params).build();
HttpPost httpPost = new HttpPost(uri);
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
System.out.println("响应状态为:"+httpResponse.getStatusLine());
HttpEntity entity = httpResponse.getEntity();
if ( entity!= null){
System.out.println("响应内容长度为:"+entity.getContentLength());
System.out.println("我告诉你一个秘密:"+EntityUtils.toString(entity));
}
} catch (URISyntaxException | IOException e) {
e.printStackTrace();
}
}
@Test
public void testPost004(){
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
User user = new User().setId(1).setName("小刘").setAge(18);
String jsonString = JSON.toJSONString(user);
StringEntity stringEntity = new StringEntity(jsonString, "utf-8");
HttpPost httpPost = new HttpPost("http://localhost:20000/postTest003");
httpPost.setEntity(stringEntity);
httpPost.setHeader("Content-Type","application/json;charset=utf-8");
try {
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
System.out.println("详情:"+EntityUtils.toString(entity));
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void postTest005(){
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("name","xiaoliu"));
try {
URI uri = new URIBuilder().setScheme("http").setHost("localhost").setPort(20000).
setPath("postTest004").setParameters(params).build();
User user = new User().setName("xiaoliu");
HttpPost httpPost = new HttpPost(uri);
httpPost.setEntity(new StringEntity(JSON.toJSONString(user),"utf-8"));
httpPost.setHeader("Content-Type","application/json;charset=utf-8");
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
System.out.println("响应状态为:"+httpResponse.getStatusLine());
HttpEntity entity = httpResponse.getEntity();
if ( entity!=null ){
System.out.println("响应内容为"+EntityUtils.toString(entity, StandardCharsets.UTF_8));
}
} catch (URISyntaxException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
3.2 对应的控制层代码
@RestController
public class HttpClientPostTest {
@PostMapping(value = "postTest001")
public String postTest001(){
return "无参的post请求";
}
@PostMapping(value = "postTest002")
public String postTest002(String name,String doing){
return name+doing;
}
@PostMapping(value = "postTest003")
public String postTest003(@RequestBody User user){
if (user.getName().equalsIgnoreCase("xiaoliu")){
return "lovely";
}
return "笨";
}
@PostMapping(value = "postTest004")
public String postTest004(String name,@RequestBody User user){
if (name.equalsIgnoreCase(user.getName())){
return "benbenbenben";
}
return "congming";
}
}
3.3 对应的实体类
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
public class User {
private int id;
private String name;
private int age;
}
4.Http上传文件
4.1 测试代码
public class FileTest {
@Test
public void fileTest() throws IOException {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("http://localhost:20000/file");
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
String fileKey = "files";
File file1 = new File("D:\\360Downloads\\111.jpg");
multipartEntityBuilder.addBinaryBody(fileKey,file1);
File file2 = new File("D:\\360Downloads\\timg.png");
multipartEntityBuilder.addBinaryBody(fileKey,file2, ContentType.DEFAULT_BINARY, URLEncoder.encode(file2.getName(),"utf-8"));
multipartEntityBuilder.addTextBody("name","xiaowang",ContentType.DEFAULT_TEXT);
multipartEntityBuilder.addTextBody("age","18",ContentType.DEFAULT_TEXT);
HttpEntity httpEntity = multipartEntityBuilder.build();
httpPost.setEntity(httpEntity);
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
System.out.println("响应的状态为:"+httpResponse.getStatusLine());
HttpEntity entity = httpResponse.getEntity();
if ( entity!=null ){
System.out.println("响应内容为:"+ EntityUtils.toString(entity));
}
}
}
4.2 controller层代码
@RestController
public class FileController {
@PostMapping(value = "file")
public String fileTest001(@RequestParam("name")String name,
@RequestParam("age") int age,
@RequestParam("files")MultipartFile[] multipartFiles) throws IOException {
if (multipartFiles.length>0){
for (MultipartFile multipartFile : multipartFiles) {
InputStream inputStream = multipartFile.getInputStream();
IOUtils.copy(inputStream,new FileOutputStream(new File(multipartFile.getOriginalFilename())));
return "success";
}
}
return "nonononon";
}
}
5.Http发送流的测试
5.1 测试代码
public class StreamTest {
@Test
public void streamTest() throws IOException {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("http://localhost:20000/stream?name=xiowangshuo");
InputStream inputStream = new ByteArrayInputStream("nihaoya,xiaoliu".getBytes());
InputStreamEntity streamEntity = new InputStreamEntity(inputStream);
httpPost.setEntity(streamEntity);
CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity entity = httpResponse.getEntity();
if ( entity!=null ){
System.out.println("响应内容为:"+ EntityUtils.toString(entity));
}
}
}
5.2controller层代码
@RestController
public class StreamController {
@PostMapping(value = "stream")
public String streamTest(@RequestParam("name") String name, InputStream inputStream) throws IOException {
StringBuffer sb = new StringBuffer();
sb.append("name的值为").append(name);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ( (line=reader.readLine())!= null){
sb.append(line);
}
return sb.toString();
}
}
6.Https测试
package com.wcc;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.io.InputStream;
import java.security.*;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Arrays;
public class HttpsTest {
private CloseableHttpClient getHttpClient(boolean isHttps) {
CloseableHttpClient httpClient;
if (isHttps) {
SSLConnectionSocketFactory sslSocketFactory;
try {
sslSocketFactory = getSocketFactory(false, null, null);
} catch (Exception e) {
throw new RuntimeException(e);
}
httpClient = HttpClientBuilder.create().setSSLSocketFactory(sslSocketFactory).build();
return httpClient;
}
httpClient = HttpClientBuilder.create().build();
return httpClient;
}
private static SSLConnectionSocketFactory getSocketFactory(boolean needVerifyCa, InputStream caInputStream, String cAalias)
throws CertificateException, NoSuchAlgorithmException, KeyStoreException,
IOException, KeyManagementException {
X509TrustManager x509TrustManager;
if (needVerifyCa) {
KeyStore keyStore = getKeyStore(caInputStream, cAalias);
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
trustManagerFactory.init(keyStore);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
}
x509TrustManager = (X509TrustManager) trustManagers[0];
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{x509TrustManager}, new SecureRandom());
return new SSLConnectionSocketFactory(sslContext);
}
x509TrustManager = new X509TrustManager() {
@Override
public void checkClientTrusted(X509Certificate[] arg0, String arg1) {
}
@Override
public void checkServerTrusted(X509Certificate[] arg0, String arg1) {
}
@Override
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
};
SSLContext sslContext = SSLContext.getInstance("TLS");
sslContext.init(null, new TrustManager[]{x509TrustManager}, new SecureRandom());
return new SSLConnectionSocketFactory(sslContext);
}
private static KeyStore getKeyStore(InputStream caInputStream, String cAalias)
throws KeyStoreException, CertificateException, IOException, NoSuchAlgorithmException {
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.load(null);
keyStore.setCertificateEntry(cAalias, certificateFactory.generateCertificate(caInputStream));
return keyStore;
}
}
Http封装好的工具类 github地址:https://github.com/Arronlong/httpclientutil