1、导入依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.46</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
2、Copy工具类
package com.wen.test.utils;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
/**
* @author 文杰
* @version 1.0
*/
@SuppressWarnings({"all"})
public class Request {
public static CloseableHttpClient getHttpClient() {
// 创建HttpClientBuilder
HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
// 设置BasicAuth
CredentialsProvider provider = new BasicCredentialsProvider();
// Create the authentication scope
AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, AuthScope.ANY_REALM);
// Create credential pair,在此处填写用户名和密码
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("admin", "12345");
// Inject the credentials
provider.setCredentials(scope, credentials);
// Set the default credentials provider
httpClientBuilder.setDefaultCredentialsProvider(provider);
// HttpClient
CloseableHttpClient httpClient = httpClientBuilder.build();
return httpClient;
}
//GET请求
public static String get(String url, JSONObject params) {
CloseableHttpClient httpClient = getHttpClient();
String sendUrl = url;
//拼接参数
if(Objects.nonNull(params) && params.size() > 0) {
sendUrl = connectParams(url,params);
}
HttpGet httpGet = new HttpGet(sendUrl);
httpGet.addHeader("Authorization", "Basic YWRtaW46MTIzNDU=");
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpGet);
HttpEntity httpEntity = response.getEntity();
System.out.println(sendUrl);
System.out.println(response.getStatusLine().getStatusCode());
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode() && null != httpEntity) {
return EntityUtils.toString(httpEntity);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
close(httpClient, response);
} catch (IOException e) {
e.printStackTrace();
}
}
throw new RuntimeException(url + "\nGet请求失败!");
}
//post请求
public static String post(String url, JSONObject params, String requestBody) {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
String sendUrl = url;
// 1.拼接参数
if (Objects.nonNull(params) && params.size() > 0) {
sendUrl = connectParams(url, params);
}
HttpPost httpPost = new HttpPost(sendUrl);
httpPost.setHeader("Content-Type", "application/json;charset=utf8");
CloseableHttpResponse response = null;
try {
// 2.设置request-body
if (StringUtils.isNotBlank(requestBody)) {
ByteArrayEntity entity = new ByteArrayEntity(requestBody.getBytes(StandardCharsets.UTF_8));
entity.setContentType("application/json");
httpPost.setEntity(entity);
}
response = httpClient.execute(httpPost);
HttpEntity httpEntity = response.getEntity();
if (HttpStatus.SC_OK == response.getStatusLine().getStatusCode() && null != httpEntity) {
return EntityUtils.toString(httpEntity);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
close(httpClient, response);
} catch (IOException e) {
e.printStackTrace();
}
}
throw new RuntimeException("调用POST请求失败!");
}
private static String connectParams(String url, JSONObject params) {
StringBuffer buffer = new StringBuffer();
buffer.append(url).append("?");
params.forEach((x, y) -> buffer.append(x).append("=").append(y).append("&"));
buffer.deleteCharAt(buffer.length() - 1);
return buffer.toString();
}
public static void close(CloseableHttpClient httpClient, CloseableHttpResponse httpResponse) throws IOException{
if (null != httpClient) {
httpClient.close();
}
if (null != httpResponse) {
httpResponse.close();
}
}
}
说明: 使用 httpclient 进行 basic auth 认证时,69行httpGet.addHeader("Authorization", "Basic YWRtaW46MTIzNDU=");这句代码很重要!!少了这句会一直报403,本文没在 post 请求的那个方法里面去加,我这里是偷懒没加,必须加不加也403