public class HttpClientUtil {
/**
* Http 基本认证
* @param username 用户名
* @param password 密码
* @return Base64加密值
*
*/
public static String getBasicAuthentication(String username, String password) {
String valueToEncode = username + ":" + password;
return "Basic " + Base64.getEncoder().encodeToString(valueToEncode.getBytes());
}
public static String sendGet(String url) {
CloseableHttpResponse resp = null;
CloseableHttpClient client = null;
try {
client = HttpClients.createDefault();
HttpGet get = new HttpGet(url);
resp = client.execute(get);
HttpEntity entity = resp.getEntity();
return EntityUtils.toString(entity, "utf-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (resp != null) {
resp.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (client != null) {
client.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static String sendGet(String url,Map<String, String> headers) {
CloseableHttpResponse resp = null;
CloseableHttpClient client = null;
try {
client = HttpClients.createDefault();
HttpGet get = new HttpGet(url);
for(String key : headers.keySet()){
get.addHeader(key, headers.get(key));
}
resp = client.execute(get);
HttpEntity entity = resp.getEntity();
return EntityUtils.toString(entity, "utf-8");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (resp != null) {
resp.close();
}
} catch (IOException e) {
e.printStackTrace();
}
try {
if (client != null) {
client.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* post请求json
* @param url
* @param json
* @return
* @throws Exception
*/
public static String sendJsonPost(String url, String json) throws Exception {
return sendPost(url, json, "application/json");
}
public static String sendPost(String url, String content, String type) {
CloseableHttpClient client = null;
CloseableHttpResponse resp = null;
try {
client = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
post.addHeader("Content-type", type);
StringEntity entity = new StringEntity(content, ContentType.create(type, "UTF-8"));
post.setEntity(entity);
resp = client.execute(post);
int statusCode = resp.getStatusLine().getStatusCode();
return EntityUtils.toString(resp.getEntity(), "utf-8");
} catch (UnsupportedCharsetException | ParseException | IOException e) {
e.printStackTrace();
} finally {
try {
if (client != null)
client.close();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
if (resp != null)
resp.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static String sendPost(String url, Map<String, String> headers, String content) {
CloseableHttpClient client = null;
CloseableHttpResponse resp = null;
try {
client = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
for(String key : headers.keySet()){
post.addHeader(key, headers.get(key));
}
StringEntity entity = new StringEntity(content, "UTF-8");
post.setEntity(entity);
resp = client.execute(post);
return EntityUtils.toString(resp.getEntity(), "utf-8");
} catch (UnsupportedCharsetException | ParseException | IOException e) {
e.printStackTrace();
} finally {
try {
if (client != null)
client.close();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
if (resp != null)
resp.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* Http Post 请求设置过期时间
* @param url 请求地址
* @param headers 请求头
* @param content 参数内容 JSON
* @return 响应
*/
public static String sendPost(String url, Map<String, String> headers, String content) {
CloseableHttpClient client = null;
CloseableHttpResponse resp = null;
try {
RequestConfig defaultRequestConfig = RequestConfig.custom()
.setConnectTimeout(5000)// 设置连接超时时间
.setConnectionRequestTimeout(5000) // 设置从 connect Manager 获取 Connection 超时时间
.setSocketTimeout(5000)// 请求获取数据的超时时间
.build();
client = HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build();
HttpPost post = new HttpPost(url);
for (String key : headers.keySet()) {
post.addHeader(key, headers.get(key));
}
StringEntity entity = new StringEntity(content, StandardCharsets.UTF_8);
post.setEntity(entity);
resp = client.execute(post);
return EntityUtils.toString(resp.getEntity(), StandardCharsets.UTF_8);
} catch (UnsupportedCharsetException | ParseException | IOException e) {
e.printStackTrace();
} finally {
try {
if (client != null)
client.close();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
if (resp != null)
resp.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* POST请求x-www-form-urlencoded方式
*/
public static String sendPost(String url,Map<String, String> headers, Map<String,String> params){
CloseableHttpClient client = null;
CloseableHttpResponse resp = null;
try {
client = HttpClients.createDefault();
HttpPost post = new HttpPost(url);
for (String key : headers.keySet()) {
post.addHeader(key, headers.get(key));
}
List<NameValuePair> parameters = new ArrayList<>();
for (Map.Entry<String, String> entry : params.entrySet()) {
parameters.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
}
UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(parameters,StandardCharsets.UTF_8);
post.setEntity(formEntity);
resp = client.execute(post);
return EntityUtils.toString(resp.getEntity(), StandardCharsets.UTF_8);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (client != null) {
client.close();
}
} catch (IOException e1) {
e1.printStackTrace();
}
try {
if (resp != null) {
resp.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
/**
* POST请求x-www-form-urlencoded方式
*/
public static String sendPostForm(String url, Map<String, String> headers, Map<String, Object> params) {
try {
// 设置请求头
org.springframework.http.HttpHeaders httpHeaders = new org.springframework.http.HttpHeaders();
for (String key : headers.keySet()) {
httpHeaders.add(key, headers.get(key));
}
// 设置参数
MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<>();
for (Map.Entry<String, Object> entry : params.entrySet()) {
parameters.add(entry.getKey(), entry.getValue());
}
// 发送请求
org.springframework.http.HttpEntity<MultiValueMap<String, Object>> requestEntity = new org.springframework.http.HttpEntity<>(parameters, httpHeaders);
ResponseEntity<String> response = new RestTemplate().exchange(url, HttpMethod.POST, requestEntity, String.class);
return response.getBody();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args) {
// 设置参数
Map<String, Object> params = new LinkedHashMap<>();
params.put("name", "Amy");
params.put("age", "22");
// 设置请求头
Map<String, String> headers = new HashMap<>();
headers.put("Content-Type", "application/x-www-form-urlencoded");
// 发送请求
String response = sendPostForm("http://127.0.0.1:8080", headers, params);
System.out.println(response);
}
public static String sendPut(String url, Map<String, String> headers, String content) {
CloseableHttpClient client = null;
CloseableHttpResponse resp = null;
try {
client = HttpClients.createDefault();
HttpPut put = new HttpPut(url);
for(String key : headers.keySet()){
put.addHeader(key, headers.get(key));
}
StringEntity entity = new StringEntity(content, "UTF-8");
put.setEntity(entity);
resp = client.execute(put);
return EntityUtils.toString(resp.getEntity(), "utf-8");
} catch (UnsupportedCharsetException | ParseException | IOException e) {
e.printStackTrace();
} finally {
try {
if (client != null)
client.close();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
if (resp != null)
resp.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static String sendPut(String url, Map<String, String> headers, byte[] content) {
CloseableHttpClient client = null;
CloseableHttpResponse resp = null;
try {
client = HttpClients.createDefault();
HttpPut put = new HttpPut(url);
for(String key : headers.keySet()){
put.addHeader(key, headers.get(key));
}
ByteArrayEntity entity = new ByteArrayEntity(content);
put.setEntity(entity);
resp = client.execute(put);
return EntityUtils.toString(resp.getEntity(), "utf-8");
} catch (UnsupportedCharsetException | ParseException | IOException e) {
e.printStackTrace();
} finally {
try {
if (client != null)
client.close();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
if (resp != null)
resp.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
public static String sendDelete(String url, Map<String, String> headers) {
CloseableHttpClient client = null;
CloseableHttpResponse resp = null;
try {
client = HttpClients.createDefault();
HttpDelete delete = new HttpDelete(url);
for(String key : headers.keySet()){
delete.addHeader(key, headers.get(key));
}
resp = client.execute(delete);
return EntityUtils.toString(resp.getEntity(), "utf-8");
} catch (UnsupportedCharsetException | ParseException | IOException e) {
e.printStackTrace();
} finally {
try {
if (client != null)
client.close();
} catch (IOException e1) {
e1.printStackTrace();
}
try {
if (resp != null)
resp.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}
HttpClient工具类
于 2022-11-21 09:56:58 首次发布
本文介绍了一个实用的HTTP客户端工具类,包含多种HTTP请求方法(GET、POST、PUT、DELETE等),支持基本认证、JSON和表单提交,并设置了合理的超时时间。
370

被折叠的 条评论
为什么被折叠?



