HttpRequestUtils.java 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. package com.happy.common.http;
  2. import com.alibaba.fastjson.JSONObject;
  3. import com.google.gson.Gson;
  4. import com.google.gson.reflect.TypeToken;
  5. import com.happy.Model.Hmap;
  6. import com.happy.common.wx.WxConfig;
  7. import com.happy.common.wx.WxConstants;
  8. import okhttp3.*;
  9. import org.apache.commons.lang3.StringUtils;
  10. import javax.net.ssl.*;
  11. import javax.servlet.http.HttpServletRequest;
  12. import java.io.BufferedReader;
  13. import java.io.IOException;
  14. import java.io.OutputStream;
  15. import java.net.HttpURLConnection;
  16. import java.net.URL;
  17. import java.util.Arrays;
  18. import java.util.HashMap;
  19. import java.util.List;
  20. import java.util.Map;
  21. import java.util.concurrent.TimeUnit;
  22. public class HttpRequestUtils {
  23. static int nc = 0; //调用次数
  24. private static final String GET = "GET";
  25. private static final String POST = "POST";
  26. private static final String PUT = "PUT";
  27. private static final String DELETE = "DELETE";
  28. private static Integer CONNECTION_TIMEOUT = WxConfig.connectionTimeout;
  29. private static Integer READ_TIMEOUT = WxConfig.readTimeout;
  30. public static Map sendPost3(String requestUrl, String requestMethod, String postData) throws Exception{
  31. Map response;
  32. HttpsURLConnection httpsUrlConnection = null;
  33. try{
  34. //创建https请求证书
  35. TrustManager[] tm={new MyX509TrustManager()};
  36. //创建SSLContext管理器对像,使用我们指定的信任管理器初始化
  37. SSLContext sslContext=SSLContext.getInstance("SSL","SunJSSE");
  38. sslContext.init(null, tm, new java.security.SecureRandom());
  39. SSLSocketFactory ssf=sslContext.getSocketFactory();
  40. // 创建URL对象
  41. URL url= new URL(requestUrl);
  42. // 创建HttpsURLConnection对象,并设置其SSLSocketFactory对象
  43. httpsUrlConnection=(HttpsURLConnection)url.openConnection();
  44. //设置ssl证书
  45. httpsUrlConnection.setSSLSocketFactory(ssf);
  46. //设置header信息
  47. httpsUrlConnection.setRequestProperty("Content-Type", "application/json");
  48. //设置User-Agent信息
  49. //httpsUrlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36");
  50. //设置可接受信息
  51. httpsUrlConnection.setDoOutput(true);
  52. //设置可输入信息
  53. httpsUrlConnection.setDoInput(true);
  54. //不使用缓存
  55. httpsUrlConnection.setUseCaches(false);
  56. //设置请求方式(GET/POST)
  57. httpsUrlConnection.setRequestMethod(requestMethod);
  58. //设置连接超时时间
  59. if (CONNECTION_TIMEOUT > 0) {
  60. httpsUrlConnection.setConnectTimeout(CONNECTION_TIMEOUT);
  61. } else {
  62. //默认10秒超时
  63. httpsUrlConnection.setConnectTimeout(10000);
  64. }
  65. //设置请求超时
  66. if (READ_TIMEOUT > 0) {
  67. httpsUrlConnection.setReadTimeout(READ_TIMEOUT);
  68. } else {
  69. //默认10秒超时
  70. httpsUrlConnection.setReadTimeout(10000);
  71. }
  72. //设置编码
  73. httpsUrlConnection.setRequestProperty("Charsert", WxConstants.DEFAULT_CHARSET);
  74. //判断是否需要提交数据
  75. if(StringUtils.equals(requestMethod,HttpsClient.METHOD_POST) && StringUtils.isNotBlank(postData)){
  76. //讲参数转换为字节提交
  77. byte[] bytes = postData.getBytes(WxConstants.DEFAULT_CHARSET);
  78. //设置头信息
  79. httpsUrlConnection.setRequestProperty("Content-Length", Integer.toString(bytes.length));
  80. //开始连接
  81. httpsUrlConnection.connect();
  82. //防止中文乱码
  83. OutputStream outputStream=httpsUrlConnection.getOutputStream();
  84. outputStream.write(postData.getBytes(WxConstants.DEFAULT_CHARSET));
  85. outputStream.flush();
  86. outputStream.close();
  87. }else{
  88. //开始连接
  89. httpsUrlConnection.connect();
  90. }
  91. response = httpsUrlConnection.getHeaderFields();
  92. }catch (Exception e){
  93. throw new Exception();
  94. }finally {
  95. if (httpsUrlConnection != null) {
  96. // 关闭连接
  97. httpsUrlConnection.disconnect();
  98. }
  99. }
  100. return response;
  101. }
  102. /**
  103. * 向指定URL发送POST方法的请求
  104. * @param
  105. * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
  106. * @param username 验证所需的用户名
  107. * @param password 验证所需的密
  108. * @param type 返回xml和json格式数据,默认xml,传入json返回json数据
  109. * @return URL 所代表远程资源的响应结果
  110. */
  111. public static HashMap<String,String> sendPost(String requestUrl, String param, String username, String password, String type) {
  112. HashMap<String,String> hmap = new HashMap<>();
  113. BufferedReader in = null;
  114. try {
  115. Map map = sendPost3(requestUrl, "POST", "123");
  116. List list = (List) map.get("WWW-Authenticate");
  117. String wwwAuth = list.get(0).toString();
  118. nc++;
  119. String urlNameString = requestUrl + (StringUtils.isNotEmpty(param) ? "?" + param : "");
  120. // 创建URL对象
  121. URL url= new URL(urlNameString);
  122. // 设置通用的请求属性
  123. String auth = setRequestProperty(wwwAuth, url, username, password, POST, type);
  124. // 支持https请求,绕过验证
  125. X509TrustManager manager = SSLSocketClientUtil.getX509TrustManager();
  126. OkHttpClient client = new OkHttpClient.Builder()
  127. .readTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS)
  128. .sslSocketFactory(SSLSocketClientUtil.getSocketFactory(manager), manager)// 忽略校验
  129. .hostnameVerifier(SSLSocketClientUtil.getHostnameVerifier())//忽略校验
  130. .build();
  131. MediaType mediaType = MediaType.parse("text/plain");
  132. RequestBody body = RequestBody.create(mediaType, "");
  133. // https://172.22.42.1/API/Web/Login
  134. Request request = new Request.Builder()
  135. .url("https://172.22.42.1/API/Web/Login")
  136. .method("POST", body)
  137. .addHeader("Authorization", auth)
  138. .addHeader("Cookie", "session=719217f94fac4389780af7b18535038329e2692bfff260fd30f1afd293aa1f28")
  139. .build();
  140. Response response = client.newCall(request).execute();
  141. Hmap.map.put("token", response.header("X-csrftoken"));
  142. Hmap.map.put("cookie", response.header("Set-Cookie"));
  143. nc = 0;
  144. response.close();
  145. } catch (Exception e) {
  146. nc = 0;
  147. throw new RuntimeException(e);
  148. } finally {
  149. try {
  150. if (in != null) {
  151. in.close();
  152. }
  153. } catch (Exception e2) {
  154. e2.printStackTrace();
  155. }
  156. }
  157. return hmap;
  158. }
  159. public static String sendPost2(String requestUrl, String token, String cookie) {
  160. StringBuilder result = new StringBuilder();
  161. BufferedReader in = null;
  162. try {
  163. // 支持https请求,绕过验证
  164. X509TrustManager manager = SSLSocketClientUtil.getX509TrustManager();
  165. OkHttpClient client = new OkHttpClient.Builder()
  166. .sslSocketFactory(SSLSocketClientUtil.getSocketFactory(manager), manager)// 忽略校验
  167. .hostnameVerifier(SSLSocketClientUtil.getHostnameVerifier())//忽略校验
  168. .build();
  169. MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
  170. RequestBody body = RequestBody.create(mediaType, "");
  171. Request request = new Request.Builder()
  172. .url(requestUrl)
  173. .method("POST", body)
  174. .addHeader("X-csrftoken", token)
  175. .addHeader("Cookie", cookie)
  176. .build();
  177. Response response = client.newCall(request).execute();
  178. result.append(response.body().string());
  179. nc = 0;
  180. response.close();
  181. } catch (Exception e) {
  182. nc = 0;
  183. throw new RuntimeException(e);
  184. } finally {
  185. try {
  186. if (in != null) {
  187. in.close();
  188. }
  189. } catch (Exception e2) {
  190. e2.printStackTrace();
  191. }
  192. }
  193. return result.toString();
  194. }
  195. public static String sendPost4(String requestUrl, String token, String cookie,JSONObject data) {
  196. StringBuilder result = new StringBuilder();
  197. BufferedReader in = null;
  198. try {
  199. // 支持https请求,绕过验证
  200. X509TrustManager manager = SSLSocketClientUtil.getX509TrustManager();
  201. OkHttpClient client = new OkHttpClient.Builder()
  202. .sslSocketFactory(SSLSocketClientUtil.getSocketFactory(manager), manager)// 忽略校验
  203. .hostnameVerifier(SSLSocketClientUtil.getHostnameVerifier())//忽略校验
  204. .build();
  205. MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
  206. RequestBody body = RequestBody.create(mediaType, String.valueOf(data));
  207. Request request = new Request.Builder()
  208. .url(requestUrl)
  209. .method("POST", body)
  210. .addHeader("X-csrftoken", token)
  211. .addHeader("Cookie", cookie)
  212. .build();
  213. Response response = client.newCall(request).execute();
  214. result.append(response.body().string());
  215. nc = 0;
  216. response.close();
  217. } catch (Exception e) {
  218. nc = 0;
  219. throw new RuntimeException(e);
  220. } finally {
  221. try {
  222. if (in != null) {
  223. in.close();
  224. }
  225. } catch (Exception e2) {
  226. e2.printStackTrace();
  227. }
  228. }
  229. return result.toString();
  230. }
  231. /**
  232. * 生成授权信息
  233. * @param authorization 上一次调用返回401的WWW-Authenticate数据
  234. * @param username 用户名
  235. * @param password 密码
  236. * @return 授权后的数据, 应放在http头的Authorization里
  237. * @throws IOException 异常
  238. */
  239. private static String getAuthorization(String authorization, String uri, String username, String password, String method) throws IOException {
  240. uri = StringUtils.isEmpty(uri) ? "/" : uri;
  241. // String temp = authorization.replaceFirst("Digest", "").trim();
  242. String temp = authorization.replaceFirst("Digest", "").trim().replace("MD5", "\"MD5\"");
  243. // String json = "{\"" + temp.replaceAll("=", "\":").replaceAll(",", ",\"") + "}";
  244. String json = withdrawJson(authorization);
  245. // String json = "{ \"realm\": \"Wowza\", \" domain\": \"/\", \" nonce\": \"MTU1NzgxMTU1NzQ4MDo2NzI3MWYxZTZkYjBiMjQ2ZGRjYTQ3ZjNiOTM2YjJjZA==\", \" algorithm\": \"MD5\", \" qop\": \"auth\" }";
  246. JSONObject jsonObject = JSONObject.parseObject(json);
  247. // String cnonce = new String(Hex.encodeHex(com.lys.util.Digests.generateSalt(8))); //客户端随机数
  248. String cnonce = "247fe9fd623c1c42";
  249. String ncstr = ("00000000" + nc).substring(Integer.toString(nc).length()); //认证的次数,第一次是1,第二次是2...
  250. // String algorithm = jsonObject.getString("algorithm");
  251. String algorithm = jsonObject.getString("algorithm");
  252. String qop = jsonObject.getString("qop");
  253. String nonce = jsonObject.getString("nonce");
  254. String realm = jsonObject.getString("realm");
  255. String response = SHA.http_da_calc_HA1(username, realm, password,
  256. nonce, ncstr, cnonce, qop,
  257. method, uri, algorithm);
  258. //组成响应authorization
  259. authorization = "Digest username=\"" + username + "\"";
  260. authorization += ",realm=\"" + realm
  261. + "\",nonce=\"" + nonce
  262. + "\",uri=\"" + uri
  263. + "\",algorithm=\"" + algorithm
  264. + "\",qop=\"" + qop
  265. + "\",nc=\"" + ncstr
  266. + "\",cnonce=\"" + cnonce
  267. + "\",response=\"" + response + "\"";
  268. return authorization;
  269. }
  270. /**
  271. * 将返回的Authrization信息转成json
  272. * @param authorization authorization info
  273. * @return 返回authrization json格式数据 如:String json = "{ \"realm\": \"Wowza\", \" domain\": \"/\", \" nonce\": \"MTU1NzgxMTU1NzQ4MDo2NzI3MWYxZTZkYjBiMjQ2ZGRjYTQ3ZjNiOTM2YjJjZA==\", \" algorithm\": \"MD5\", \" qop\": \"auth\" }";
  274. */
  275. private static String withdrawJson(String authorization) {
  276. String temp = authorization.replaceFirst("Digest", "").trim().replaceAll("\"", "");
  277. // String noncetemp = temp.substring(temp.indexOf("nonce="), temp.indexOf("uri="));
  278. // String json = "{\"" + temp.replaceAll("=", "\":").replaceAll(",", ",\"") + "}";
  279. String[] split = temp.split(",");
  280. Map map = new HashMap<>();
  281. Arrays.asList(split).forEach(c -> {
  282. String c1 = c.replaceFirst("=", ":");
  283. String[] split1 = c1.split(":");
  284. map.put(split1[0].trim(), split1[1].trim());
  285. });
  286. return JSONObject.toJSONString(map);
  287. }
  288. /**
  289. * HTTP set request property
  290. * @param wwwAuth 授权auth
  291. * @param realUrl 实际url
  292. * @param username 验证所需的用户名
  293. * @param password 验证所需的密码
  294. * @param method 请求方式
  295. * @param type 返回xml和json格式数据,默认xml,传入json返回json数据
  296. */
  297. private static String setRequestProperty(String wwwAuth, URL realUrl, String username, String password, String method, String type)
  298. throws IOException {
  299. //授权信息
  300. return getAuthorization(wwwAuth, realUrl.getPath(), username, password, method);
  301. }
  302. /**
  303. * 格式化请求返回信息,支持json和xml格式
  304. * @param connection HttpConnection
  305. * @param type 指定返回数据格式,json、xml,默认xml
  306. * @return 返回数据
  307. */
  308. private static String formatResultInfo(HttpURLConnection connection, String type) throws IOException {
  309. String result = "";
  310. if ("json".equals(type)) {
  311. result = String.format("{\"errCode\":%s, \"message\":%s}", connection.getResponseCode(), connection.getResponseMessage());
  312. } else {
  313. result = String.format(" <?xml version=\"1.0\" encoding=\"UTF-8\" ?> "
  314. + " "
  315. + " %d"
  316. + " %s"
  317. + " ", connection.getResponseCode(), connection.getResponseMessage());
  318. }
  319. return result;
  320. }
  321. public static void main(String[] args) {
  322. }
  323. }