355 lines
13 KiB
Plaintext
355 lines
13 KiB
Plaintext
package com.sercurityControl.proteam.util;
|
||
|
||
|
||
import com.alibaba.fastjson2.JSON;
|
||
import com.alibaba.fastjson2.JSONObject;
|
||
import com.securityControl.common.core.utils.aes.StringHelper;
|
||
import okhttp3.*;
|
||
import org.apache.http.HttpResponse;
|
||
import org.apache.http.StatusLine;
|
||
import org.apache.http.client.methods.HttpPost;
|
||
import org.apache.http.entity.ContentType;
|
||
import org.apache.http.entity.StringEntity;
|
||
import org.apache.http.impl.client.CloseableHttpClient;
|
||
import org.apache.http.impl.client.HttpClientBuilder;
|
||
import org.springframework.http.HttpEntity;
|
||
import org.springframework.http.HttpHeaders;
|
||
import org.springframework.http.MediaType;
|
||
import org.springframework.http.ResponseEntity;
|
||
import org.springframework.util.DigestUtils;
|
||
import org.springframework.util.StringUtils;
|
||
import org.springframework.web.client.RestTemplate;
|
||
|
||
import java.io.*;
|
||
import java.net.URL;
|
||
import java.net.URLConnection;
|
||
import java.util.Arrays;
|
||
import java.util.HashMap;
|
||
import java.util.List;
|
||
import java.util.Map;
|
||
|
||
/**
|
||
* @author 吕继龙
|
||
* http请求类
|
||
*/
|
||
public class HttpClient {
|
||
static RestTemplate restTemplate;
|
||
|
||
/**
|
||
* 生成post请求的JSON请求参数
|
||
* 请求示例:
|
||
* {
|
||
* "id":1,
|
||
* "name":"张耀烽"
|
||
* }
|
||
*
|
||
* @return
|
||
*/
|
||
private static HttpEntity<Map<String, String>> generatePostJson(Map<String, String> jsonMap, String token) {
|
||
|
||
//如果需要其它的请求头信息、都可以在这里追加
|
||
HttpHeaders httpHeaders = new HttpHeaders();
|
||
|
||
MediaType type = MediaType.parseMediaType("application/json;charset=UTF-8");
|
||
|
||
if (StringHelper.isNotEmpty(token)) {
|
||
httpHeaders.add("token", token);
|
||
}
|
||
if (jsonMap == null) {
|
||
jsonMap = new HashMap<>(16);
|
||
}
|
||
|
||
HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(jsonMap, httpHeaders);
|
||
return httpEntity;
|
||
}
|
||
|
||
/**
|
||
* post请求、请求参数为json
|
||
*
|
||
* @return
|
||
*/
|
||
public static String sendPost(String url, String token, Map<String, String> jsonMap) {
|
||
restTemplate = new RestTemplate();
|
||
ResponseEntity<String> apiResponse = restTemplate.postForEntity
|
||
(
|
||
url,
|
||
generatePostJson(jsonMap, token),
|
||
String.class
|
||
);
|
||
return apiResponse.getBody();
|
||
}
|
||
|
||
private static int nc = 0;
|
||
private static OkHttpClient client = new OkHttpClient().newBuilder()
|
||
.build();
|
||
|
||
/**
|
||
* 向指定URL发送GET方法的请求Authenticate
|
||
*
|
||
* @param url 发送请求的URL
|
||
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
|
||
* @return URL 所代表远程资源的响应结果
|
||
*/
|
||
public static String sendGetAuthenticate(String url, String param) {
|
||
String result = "";
|
||
BufferedReader in = null;
|
||
try {
|
||
String urlNameString = url;
|
||
URL realUrl = new URL(urlNameString);
|
||
// 打开和URL之间的连接
|
||
URLConnection connection = realUrl.openConnection();
|
||
// 设置通用的请求属性
|
||
connection.setRequestProperty("accept", "*/*");
|
||
connection.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
|
||
connection.setRequestProperty("connection", "Keep-Alive");
|
||
connection.setRequestProperty("user-agent",
|
||
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
|
||
// 建立实际的连接
|
||
connection.connect();
|
||
// 获取所有响应头字段
|
||
Map<String, List<String>> map = connection.getHeaderFields();
|
||
// 遍历所有的响应头字段
|
||
result = getAuthorization(map.get("WWW-Authenticate").get(0), param, "admin", "123456", "POST");
|
||
} catch (Exception e) {
|
||
System.out.println("发送GET请求出现异常!" + e);
|
||
e.printStackTrace();
|
||
}
|
||
// 使用finally块来关闭输入流
|
||
finally {
|
||
try {
|
||
if (in != null) {
|
||
in.close();
|
||
}
|
||
} catch (Exception e2) {
|
||
e2.printStackTrace();
|
||
}
|
||
}
|
||
return result;
|
||
}
|
||
|
||
/**
|
||
* 向指定 URL 发送POST方法的请求
|
||
*
|
||
* @param url 发送请求的 URL
|
||
* @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
|
||
* @return 所代表远程资源的响应结果
|
||
*/
|
||
|
||
public static String sendPost(String url, String param) {
|
||
String result = "";
|
||
okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
|
||
RequestBody body = RequestBody.create(mediaType, param);
|
||
Request request = new Request.Builder()
|
||
.url(url)
|
||
.method("POST", body)
|
||
.addHeader("Content-Type", "application/json")
|
||
.addHeader("Cookie", "connect.sid=s%3AJNX6IuWZL.rdxyEj7NkC4jXU645BFGtcS98rQ0%2Bibff2nUNJKRuGg")
|
||
.build();
|
||
try {
|
||
Response response = client.newCall(request).execute();
|
||
result = response.body().string();
|
||
} catch (Exception e) {
|
||
e.printStackTrace();
|
||
}
|
||
return result;
|
||
}
|
||
|
||
|
||
/**
|
||
* 向指定 URL 发送POST方法的请求
|
||
*
|
||
* @param url 发送请求的 URL
|
||
* @param param 请求参数
|
||
* @param authenticate 摘要信息
|
||
* @return 所代表远程资源的响应结果
|
||
*/
|
||
public static String sendPostAuthenticate(String url, String param, String authenticate) {
|
||
String result = "";
|
||
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
|
||
try {
|
||
URL realUrl = new URL(url);
|
||
HttpPost httpPost = new HttpPost(url);
|
||
// 打开和URL之间的连接
|
||
httpPost.setHeader("Connection", "keep-alive");
|
||
httpPost.setHeader("Authorization", authenticate);
|
||
//这里的“application/json” 可以更换因为本人是传的json参数所以用的这个
|
||
org.apache.http.HttpEntity entityParam = new StringEntity(param, ContentType.create("application/json", "UTF-8"));
|
||
//把参数添加到post请求
|
||
httpPost.setEntity(entityParam);
|
||
HttpResponse response = httpClient.execute(httpPost);
|
||
//获取请求对象中的响应行对象
|
||
StatusLine statusLine = response.getStatusLine();
|
||
int responseCode = statusLine.getStatusCode();
|
||
if (responseCode == 200) {
|
||
//获取响应信息
|
||
org.apache.http.HttpEntity entity = response.getEntity();
|
||
InputStream input = entity.getContent();
|
||
BufferedReader br = new BufferedReader(new InputStreamReader(input, "utf-8"));
|
||
result = br.readLine();
|
||
br.close();
|
||
input.close();
|
||
} else {
|
||
System.out.println("响应失败");
|
||
}
|
||
} catch (Exception e) {
|
||
System.out.println("发送 POST 请求出现异常!" + e);
|
||
e.printStackTrace();
|
||
}
|
||
return result;
|
||
}
|
||
|
||
/**
|
||
* 生成授权信息
|
||
*
|
||
* @param authorization 上一次调用返回401的WWW-Authenticate数据
|
||
* @param username 用户名
|
||
* @param password 密码
|
||
* @return 授权后的数据, 应放在http头的Authorization里
|
||
* @throws IOException 异常
|
||
*/
|
||
private static String getAuthorization(String authorization, String uri, String username, String password, String method) throws IOException {
|
||
|
||
uri = StringUtils.isEmpty(uri) ? "/" : uri;
|
||
String temp = authorization.replaceFirst("Digest", "").trim().replace("MD5", "\"MD5\"");
|
||
String json = withdrawJson(authorization);
|
||
JSONObject jsonObject = JSON.parseObject(json);
|
||
//客户端随机数
|
||
String cnonce = Digests.generateSalt2(8);
|
||
//认证的次数,第一次是1,第二次是2...
|
||
String ncstr = ("00000000" + 1).substring(Integer.toString(1).length());
|
||
String algorithm = jsonObject.getString("algorithm");
|
||
String qop = jsonObject.getString("qop");
|
||
String nonce = jsonObject.getString("nonce");
|
||
String realm = jsonObject.getString("realm");
|
||
|
||
String response = Digests.http_da_calc_HA1(username, realm, DigestUtils.md5DigestAsHex(password.getBytes()),
|
||
nonce, ncstr, cnonce, qop,
|
||
method, uri, algorithm);
|
||
|
||
//组成响应authorization
|
||
authorization = "Digest username=\"" + username + "\"," + temp;
|
||
authorization += ",uri=\"" + uri
|
||
+ "\",nc=\"" + ncstr
|
||
+ "\",cnonce=\"" + cnonce
|
||
+ "\",response=\"" + response + "\"";
|
||
return authorization;
|
||
}
|
||
|
||
/**
|
||
* 将返回的Authrization信息转成json
|
||
*
|
||
* @param authorization authorization info
|
||
* @return 返回authrization json格式数据 如:String json = "{ \"realm\": \"Wowza\", \" domain\": \"/\", \" nonce\": \"MTU1NzgxMTU1NzQ4MDo2NzI3MWYxZTZkYjBiMjQ2ZGRjYTQ3ZjNiOTM2YjJjZA==\", \" algorithm\": \"MD5\", \" qop\": \"auth\" }";
|
||
*/
|
||
private static String withdrawJson(String authorization) {
|
||
String temp = authorization.replaceFirst("Digest", "").trim().replaceAll("\"", "");
|
||
String[] split = temp.split(",");
|
||
Map<String, String> map = new HashMap<>(16);
|
||
Arrays.asList(split).forEach(c -> {
|
||
String c1 = c.replaceFirst("=", ":");
|
||
String[] split1 = c1.split(":");
|
||
map.put(split1[0].trim(), split1[1].trim());
|
||
});
|
||
return JSONObject.toJSONString(map);
|
||
}
|
||
/**
|
||
* 删除人员信息
|
||
* @param url 地址
|
||
* @param authorization 摘要信息
|
||
* @param param 数据体
|
||
* @return
|
||
**/
|
||
public static String postDeletePerson(String url, String authorization, String param){
|
||
String result = "";
|
||
okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
|
||
RequestBody body = RequestBody.create(mediaType, param);
|
||
Request request = new Request.Builder()
|
||
.url(url)
|
||
.method("POST", body)
|
||
.addHeader("Authorization", authorization)
|
||
.build();
|
||
try {
|
||
Response response = client.newCall(request).execute();
|
||
result = response.body().string();
|
||
} catch (Exception e) {
|
||
e.printStackTrace();
|
||
}
|
||
return result;
|
||
}
|
||
/**
|
||
* 删除人员图片
|
||
* @param url 地址
|
||
* @param authorization 摘要信息
|
||
* @param param 数据体
|
||
* @return
|
||
**/
|
||
public static String postDeleteImage(String url, String authorization, String param){
|
||
String result = "";
|
||
okhttp3.MediaType mediaType = okhttp3.MediaType.parse("application/json");
|
||
RequestBody body = RequestBody.create(mediaType, param);
|
||
Request request = new Request.Builder()
|
||
.url(url)
|
||
.method("POST", body)
|
||
.addHeader("Authorization", authorization)
|
||
.build();
|
||
try {
|
||
Response response = client.newCall(request).execute();
|
||
result = response.body().string();
|
||
} catch (Exception e) {
|
||
e.printStackTrace();
|
||
}
|
||
return result;
|
||
}
|
||
|
||
public static String sendGet(String url, String token, String param) {
|
||
String result = "";
|
||
BufferedReader in = null;
|
||
|
||
try {
|
||
String urlNameString = url + "?" + param;
|
||
URL realUrl = new URL(urlNameString);
|
||
// 打开和URL之间的连接
|
||
URLConnection connection = realUrl.openConnection();
|
||
// 设置通用的请求属性
|
||
connection.setRequestProperty("accept", "*/*");
|
||
connection.setRequestProperty("connection", "Keep-Alive");
|
||
connection.setRequestProperty("user-agent",
|
||
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
|
||
// 建立实际的连接
|
||
connection.setRequestProperty("token", token);
|
||
connection.connect();
|
||
// 获取所有响应头字段
|
||
Map<String, List<String>> map = connection.getHeaderFields();
|
||
// 遍历所有的响应头字段
|
||
for (String key : map.keySet()) {
|
||
System.out.println(key + "--->" + map.get(key));
|
||
}
|
||
// 定义 BufferedReader输入流来读取URL的响应
|
||
in = new BufferedReader(new InputStreamReader(
|
||
connection.getInputStream()));
|
||
String line;
|
||
while ((line = in.readLine()) != null) {
|
||
result += line;
|
||
}
|
||
} catch (Exception e) {
|
||
System.out.println("发送GET请求出现异常!" + e);
|
||
e.printStackTrace();
|
||
}
|
||
// 使用finally块来关闭输入流
|
||
finally {
|
||
try {
|
||
if (in != null) {
|
||
in.close();
|
||
}
|
||
} catch (Exception e2) {
|
||
e2.printStackTrace();
|
||
}
|
||
}
|
||
return result;
|
||
}
|
||
|
||
|
||
|
||
|
||
}
|