HttpClient工具类

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;
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值