| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342 |
- package com.happy.common.http;
- import com.alibaba.fastjson.JSONObject;
- import com.google.gson.Gson;
- import com.google.gson.reflect.TypeToken;
- import com.happy.Model.Hmap;
- import com.happy.common.wx.WxConfig;
- import com.happy.common.wx.WxConstants;
- import okhttp3.*;
- import org.apache.commons.lang3.StringUtils;
- import javax.net.ssl.*;
- import javax.servlet.http.HttpServletRequest;
- import java.io.BufferedReader;
- import java.io.IOException;
- import java.io.OutputStream;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.util.Arrays;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import java.util.concurrent.TimeUnit;
- public class HttpRequestUtils {
- static int nc = 0; //调用次数
- private static final String GET = "GET";
- private static final String POST = "POST";
- private static final String PUT = "PUT";
- private static final String DELETE = "DELETE";
- private static Integer CONNECTION_TIMEOUT = WxConfig.connectionTimeout;
- private static Integer READ_TIMEOUT = WxConfig.readTimeout;
- public static Map sendPost3(String requestUrl, String requestMethod, String postData) throws Exception{
- Map response;
- HttpsURLConnection httpsUrlConnection = null;
- try{
- //创建https请求证书
- TrustManager[] tm={new MyX509TrustManager()};
- //创建SSLContext管理器对像,使用我们指定的信任管理器初始化
- SSLContext sslContext=SSLContext.getInstance("SSL","SunJSSE");
- sslContext.init(null, tm, new java.security.SecureRandom());
- SSLSocketFactory ssf=sslContext.getSocketFactory();
- // 创建URL对象
- URL url= new URL(requestUrl);
- // 创建HttpsURLConnection对象,并设置其SSLSocketFactory对象
- httpsUrlConnection=(HttpsURLConnection)url.openConnection();
- //设置ssl证书
- httpsUrlConnection.setSSLSocketFactory(ssf);
- //设置header信息
- httpsUrlConnection.setRequestProperty("Content-Type", "application/json");
- //设置User-Agent信息
- //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");
- //设置可接受信息
- httpsUrlConnection.setDoOutput(true);
- //设置可输入信息
- httpsUrlConnection.setDoInput(true);
- //不使用缓存
- httpsUrlConnection.setUseCaches(false);
- //设置请求方式(GET/POST)
- httpsUrlConnection.setRequestMethod(requestMethod);
- //设置连接超时时间
- if (CONNECTION_TIMEOUT > 0) {
- httpsUrlConnection.setConnectTimeout(CONNECTION_TIMEOUT);
- } else {
- //默认10秒超时
- httpsUrlConnection.setConnectTimeout(10000);
- }
- //设置请求超时
- if (READ_TIMEOUT > 0) {
- httpsUrlConnection.setReadTimeout(READ_TIMEOUT);
- } else {
- //默认10秒超时
- httpsUrlConnection.setReadTimeout(10000);
- }
- //设置编码
- httpsUrlConnection.setRequestProperty("Charsert", WxConstants.DEFAULT_CHARSET);
- //判断是否需要提交数据
- if(StringUtils.equals(requestMethod,HttpsClient.METHOD_POST) && StringUtils.isNotBlank(postData)){
- //讲参数转换为字节提交
- byte[] bytes = postData.getBytes(WxConstants.DEFAULT_CHARSET);
- //设置头信息
- httpsUrlConnection.setRequestProperty("Content-Length", Integer.toString(bytes.length));
- //开始连接
- httpsUrlConnection.connect();
- //防止中文乱码
- OutputStream outputStream=httpsUrlConnection.getOutputStream();
- outputStream.write(postData.getBytes(WxConstants.DEFAULT_CHARSET));
- outputStream.flush();
- outputStream.close();
- }else{
- //开始连接
- httpsUrlConnection.connect();
- }
- response = httpsUrlConnection.getHeaderFields();
- }catch (Exception e){
- throw new Exception();
- }finally {
- if (httpsUrlConnection != null) {
- // 关闭连接
- httpsUrlConnection.disconnect();
- }
- }
- return response;
- }
- /**
- * 向指定URL发送POST方法的请求
- * @param
- * @param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
- * @param username 验证所需的用户名
- * @param password 验证所需的密
- * @param type 返回xml和json格式数据,默认xml,传入json返回json数据
- * @return URL 所代表远程资源的响应结果
- */
- public static HashMap<String,String> sendPost(String requestUrl, String param, String username, String password, String type) {
- HashMap<String,String> hmap = new HashMap<>();
- BufferedReader in = null;
- try {
- Map map = sendPost3(requestUrl, "POST", "123");
- List list = (List) map.get("WWW-Authenticate");
- String wwwAuth = list.get(0).toString();
- nc++;
- String urlNameString = requestUrl + (StringUtils.isNotEmpty(param) ? "?" + param : "");
- // 创建URL对象
- URL url= new URL(urlNameString);
- // 设置通用的请求属性
- String auth = setRequestProperty(wwwAuth, url, username, password, POST, type);
- // 支持https请求,绕过验证
- X509TrustManager manager = SSLSocketClientUtil.getX509TrustManager();
- OkHttpClient client = new OkHttpClient.Builder()
- .readTimeout(READ_TIMEOUT, TimeUnit.MILLISECONDS)
- .sslSocketFactory(SSLSocketClientUtil.getSocketFactory(manager), manager)// 忽略校验
- .hostnameVerifier(SSLSocketClientUtil.getHostnameVerifier())//忽略校验
- .build();
- MediaType mediaType = MediaType.parse("text/plain");
- RequestBody body = RequestBody.create(mediaType, "");
- // https://172.22.42.1/API/Web/Login
- Request request = new Request.Builder()
- .url("https://172.22.42.1/API/Web/Login")
- .method("POST", body)
- .addHeader("Authorization", auth)
- .addHeader("Cookie", "session=719217f94fac4389780af7b18535038329e2692bfff260fd30f1afd293aa1f28")
- .build();
- Response response = client.newCall(request).execute();
- Hmap.map.put("token", response.header("X-csrftoken"));
- Hmap.map.put("cookie", response.header("Set-Cookie"));
- nc = 0;
- response.close();
- } catch (Exception e) {
- nc = 0;
- throw new RuntimeException(e);
- } finally {
- try {
- if (in != null) {
- in.close();
- }
- } catch (Exception e2) {
- e2.printStackTrace();
- }
- }
- return hmap;
- }
- public static String sendPost2(String requestUrl, String token, String cookie) {
- StringBuilder result = new StringBuilder();
- BufferedReader in = null;
- try {
- // 支持https请求,绕过验证
- X509TrustManager manager = SSLSocketClientUtil.getX509TrustManager();
- OkHttpClient client = new OkHttpClient.Builder()
- .sslSocketFactory(SSLSocketClientUtil.getSocketFactory(manager), manager)// 忽略校验
- .hostnameVerifier(SSLSocketClientUtil.getHostnameVerifier())//忽略校验
- .build();
- MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
- RequestBody body = RequestBody.create(mediaType, "");
- Request request = new Request.Builder()
- .url(requestUrl)
- .method("POST", body)
- .addHeader("X-csrftoken", token)
- .addHeader("Cookie", cookie)
- .build();
- Response response = client.newCall(request).execute();
- result.append(response.body().string());
- nc = 0;
- response.close();
- } catch (Exception e) {
- nc = 0;
- throw new RuntimeException(e);
- } finally {
- try {
- if (in != null) {
- in.close();
- }
- } catch (Exception e2) {
- e2.printStackTrace();
- }
- }
- return result.toString();
- }
- public static String sendPost4(String requestUrl, String token, String cookie,JSONObject data) {
- StringBuilder result = new StringBuilder();
- BufferedReader in = null;
- try {
- // 支持https请求,绕过验证
- X509TrustManager manager = SSLSocketClientUtil.getX509TrustManager();
- OkHttpClient client = new OkHttpClient.Builder()
- .sslSocketFactory(SSLSocketClientUtil.getSocketFactory(manager), manager)// 忽略校验
- .hostnameVerifier(SSLSocketClientUtil.getHostnameVerifier())//忽略校验
- .build();
- MediaType mediaType = MediaType.parse("application/json; charset=utf-8");
- RequestBody body = RequestBody.create(mediaType, String.valueOf(data));
- Request request = new Request.Builder()
- .url(requestUrl)
- .method("POST", body)
- .addHeader("X-csrftoken", token)
- .addHeader("Cookie", cookie)
- .build();
- Response response = client.newCall(request).execute();
- result.append(response.body().string());
- nc = 0;
- response.close();
- } catch (Exception e) {
- nc = 0;
- throw new RuntimeException(e);
- } finally {
- try {
- if (in != null) {
- in.close();
- }
- } catch (Exception e2) {
- e2.printStackTrace();
- }
- }
- return result.toString();
- }
- /**
- * 生成授权信息
- * @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();
- String temp = authorization.replaceFirst("Digest", "").trim().replace("MD5", "\"MD5\"");
- // String json = "{\"" + temp.replaceAll("=", "\":").replaceAll(",", ",\"") + "}";
- String json = withdrawJson(authorization);
- // String json = "{ \"realm\": \"Wowza\", \" domain\": \"/\", \" nonce\": \"MTU1NzgxMTU1NzQ4MDo2NzI3MWYxZTZkYjBiMjQ2ZGRjYTQ3ZjNiOTM2YjJjZA==\", \" algorithm\": \"MD5\", \" qop\": \"auth\" }";
- JSONObject jsonObject = JSONObject.parseObject(json);
- // String cnonce = new String(Hex.encodeHex(com.lys.util.Digests.generateSalt(8))); //客户端随机数
- String cnonce = "247fe9fd623c1c42";
- String ncstr = ("00000000" + nc).substring(Integer.toString(nc).length()); //认证的次数,第一次是1,第二次是2...
- // String algorithm = jsonObject.getString("algorithm");
- String algorithm = jsonObject.getString("algorithm");
- String qop = jsonObject.getString("qop");
- String nonce = jsonObject.getString("nonce");
- String realm = jsonObject.getString("realm");
- String response = SHA.http_da_calc_HA1(username, realm, password,
- nonce, ncstr, cnonce, qop,
- method, uri, algorithm);
- //组成响应authorization
- authorization = "Digest username=\"" + username + "\"";
- authorization += ",realm=\"" + realm
- + "\",nonce=\"" + nonce
- + "\",uri=\"" + uri
- + "\",algorithm=\"" + algorithm
- + "\",qop=\"" + qop
- + "\",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 noncetemp = temp.substring(temp.indexOf("nonce="), temp.indexOf("uri="));
- // String json = "{\"" + temp.replaceAll("=", "\":").replaceAll(",", ",\"") + "}";
- String[] split = temp.split(",");
- Map map = new HashMap<>();
- 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);
- }
- /**
- * HTTP set request property
- * @param wwwAuth 授权auth
- * @param realUrl 实际url
- * @param username 验证所需的用户名
- * @param password 验证所需的密码
- * @param method 请求方式
- * @param type 返回xml和json格式数据,默认xml,传入json返回json数据
- */
- private static String setRequestProperty(String wwwAuth, URL realUrl, String username, String password, String method, String type)
- throws IOException {
- //授权信息
- return getAuthorization(wwwAuth, realUrl.getPath(), username, password, method);
- }
- /**
- * 格式化请求返回信息,支持json和xml格式
- * @param connection HttpConnection
- * @param type 指定返回数据格式,json、xml,默认xml
- * @return 返回数据
- */
- private static String formatResultInfo(HttpURLConnection connection, String type) throws IOException {
- String result = "";
- if ("json".equals(type)) {
- result = String.format("{\"errCode\":%s, \"message\":%s}", connection.getResponseCode(), connection.getResponseMessage());
- } else {
- result = String.format(" <?xml version=\"1.0\" encoding=\"UTF-8\" ?> "
- + " "
- + " %d"
- + " %s"
- + " ", connection.getResponseCode(), connection.getResponseMessage());
- }
- return result;
- }
- public static void main(String[] args) {
- }
- }
|