依赖
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.6</version>
</dependency>
HTTPS请求认证
public static void doDownload(String url, String body,String urlPath) {
//创建post请求对象
log.info("请求路径:" + url);
HttpPost httpGet = new HttpPost(url);
String result = "";
//配置超时时间
RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).build();
httpGet.setConfig(config);
//使用之前写的方法创建httpClient实例
CloseableHttpClient httpClient = createSSLClientDefault();
try {
httpGet.setHeader("accept", "application/json");
httpGet.setHeader("Content-Type", "application/json;charset=UTF-8");
// httpPost.setHeader("st-auth-token", token);
if (!StringUtils.isEmpty(body)) {
log.info("请求体:" + new StringEntity(body, "UTF-8") + " String:" + body);
httpGet.setEntity(new StringEntity(body, "UTF-8"));
}
//使用CloseableHttpClient发送请求
CloseableHttpResponse response = httpClient.execute(httpGet);
log.info("POST请求 " + response);
//获取返回code
int statusCode = response.getStatusLine().getStatusCode();
log.info("状态码" + statusCode);
//根据返回code进行处理
if (statusCode == 200) {
log.info("请求:" + statusCode);
//获取响应结果
HttpEntity entity = response.getEntity();
response.setHeader("Content-Type", "application/octet-stream");
InputStream is = entity.getContent();
int cache = 10 * 1024;
// FileOutputStream fileout = new FileOutputStream("/Users/linyanxia/Downloads/FileZilla/getKL.ofd");
FileOutputStream fileout = new FileOutputStream(urlPath);
byte[] buffer = new byte[cache];
int ch = 0;
while ((ch = is.read(buffer)) != -1) {
fileout.write(buffer, 0, ch);
}
is.close();
fileout.flush();
fileout.close();
log.info("请求成功");
}
} catch (IOException e) {
log.info("请求失败");
log.info(e.getLocalizedMessage());
e.printStackTrace();
log.info("POST错误信息" + e);
}
}
public static CloseableHttpClient createSSLClientDefault() {
try {
//使用 loadTrustMaterial() 方法实现一个信任策略,信任所有证书
SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy() {
// 信任所有
public boolean isTrusted(X509Certificate[] chain, String authType) throws CertificateException {
return true;
}
}).build();
//NoopHostnameVerifier类: 作为主机名验证工具,实质上关闭了主机名验证,它接受任何
//有效的SSL会话并匹配到目标主机。
HostnameVerifier hostnameVerifier = NoopHostnameVerifier.INSTANCE;
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
return HttpClients.custom().setSSLSocketFactory(sslsf).build();
} catch (KeyManagementException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (KeyStoreException e) {
e.printStackTrace();
}
return HttpClients.createDefault();
}
简单GET请求
public static String Get(String url) throws IOException {
// 创建对象
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// GET请求路径
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("Content-Type", "application/json;charset=utf8");
// 响应
CloseableHttpResponse response = httpClient.execute(httpGet);
// 获取状态码
int statusCode = response.getStatusLine().getStatusCode();
// 只能获取一次
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
return result;
}
简单POST请求
public static String Post(String url,Object param) throws IOException {
// 创建对象
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// POST请求路径
HttpPost httpPost = new HttpPost(url);
httpPost.setHeader("Content-Type", "application/json;charset=utf8");
// 放入请求体
JSONObject jsonObject = new JSONObject();
jsonObject.put("size", "1");
jsonObject.put("current", "1");
StringEntity entity = new StringEntity(jsonObject.toString(), "UTF-8");
httpPost.setEntity(entity);
// 响应
CloseableHttpResponse response = httpClient.execute(httpPost);
// 获取对象(只能获取一次response.getEntity())
String result = EntityUtils.toString(response.getEntity());
return result;
}
POST请求
/**
*
* @param url 请求路径
* @param header 请求头
* @param param 对象参数
* @param path 拼接参数
* @param type 拼接路径true:PathVariable拼接,false:RequestParam拼接,""为不拼接
* @return
*/
public static String isPost(String url,Map<String,String> header,Object param,
Map<String,String> path,String type){
// 创建
CloseableHttpClient httpClient=HttpClientBuilder.create().build();
CloseableHttpResponse response=null;
String uri="";
try {
// 是否需要路径拼接
if (!type.isEmpty()){
if (type.equals("true")){
// PathVariable拼接
if (!path.isEmpty()){
for (String key:path.keySet()){
uri+="/"+path.get(key);
}
// System.out.println("拼接路径: "+uri);
}
}else if (type.equals("false")){
// RequestParam拼接
if (!path.isEmpty()){
uri="?";
for (String key:path.keySet()){
uri+=key+"="+path.get(key)+"&";
}
uri=uri.substring(0,uri.length()-1);
}
}
}
url=url+uri;
System.out.println("访问路径: "+url);
// HttpPost
HttpPost httpPost = new HttpPost(url);
// 判断是否为空
if (!header.isEmpty()){
for (String key:header.keySet()){
// 存入header
httpPost.addHeader(key,header.get(key));
}
}
httpPost.setHeader("Content-Type", "application/json;charset=utf8");
// 转化为JSON串
String jsonString = JSON.toJSONString(param);
StringEntity entity = new StringEntity(jsonString, "UTF-8");
// 传入参数
httpPost.setEntity(entity);
// 获取响应体
response=httpClient.execute(httpPost);
// 获取响应体状态
// System.out.println(response.getStatusLine().getStatusCode());
// HttpClient只允许获取一次getEntity
String result = EntityUtils.toString(response.getEntity());
System.out.println("响应状态: "+response.getStatusLine().getStatusCode());
System.out.println("响应数据: "+result);
return result;
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
try {
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return "执行发生错误!";
}
GET
/**
* httpClient get请求
* @param url 请求url
* @param param 请求参数 form提交适用
* @return 可能为空 需要处理
* @throws Exception
*
*/
public static String sendHttpsGet(String url, String param, String sign) throws Exception {
String result = "";
CloseableHttpClient httpClient = null;
try {
httpClient = getHttpClient();
JSONObject parse = (JSONObject) JSONObject.parse(param);
Integer pageCount = (Integer) parse.get("pageCount");
Integer pageNo = (Integer) parse.get("pageNo");
if (pageCount==pageNo){
}else{
url+="?pageCount="+pageCount+"/pageNo="+pageNo;
}
log.info("请求地址: "+url);
HttpGet httpGet = new HttpGet(url);
/**
* 设置请求头
*/
httpGet.addHeader("Content-Type", "application/json");
httpGet.addHeader("Authorization",sign);
// httpPost.addHeader("passWord","3er4#ER$3er4#ER$12");
/**
* 设置请求参数
*/
// System.out.println("参数 "+param);
// StringEntity stringEntity = new StringEntity(param, "utf-8");
// httpGet.setEntity(stringEntity);
HttpResponse httpResponse = httpClient.execute(httpGet);
int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
HttpEntity resEntity = httpResponse.getEntity();
result = EntityUtils.toString(resEntity);
} else {
result = readHttpResponse(httpResponse);
}
} catch (Exception e) {
log.info("send lookalike http get request failed, HttpException"+e);
throw e;
} finally {
}
return result;
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。