| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585 |
- 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.Message;
- import com.happy.Model.Visitor;
- import com.happy.common.wx.WxConfig;
- import com.happy.common.wx.WxConstants;
- import com.happy.common.wx.WxUtil;
- import com.happy.unitil.CreateSign1;
- import org.apache.commons.lang3.StringUtils;
- import org.apache.http.HttpEntity;
- import org.apache.http.NameValuePair;
- import org.apache.http.client.ClientProtocolException;
- import org.apache.http.client.config.RequestConfig;
- import org.apache.http.client.entity.UrlEncodedFormEntity;
- import org.apache.http.client.methods.CloseableHttpResponse;
- import org.apache.http.client.methods.HttpGet;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.impl.client.CloseableHttpClient;
- import org.apache.http.impl.client.HttpClients;
- import org.apache.http.message.BasicNameValuePair;
- import org.apache.http.util.EntityUtils;
- import javax.net.ssl.HttpsURLConnection;
- import javax.net.ssl.SSLContext;
- import javax.net.ssl.SSLSocketFactory;
- import javax.net.ssl.TrustManager;
- import java.io.*;
- import java.net.HttpURLConnection;
- import java.net.URL;
- import java.net.URLConnection;
- import java.text.SimpleDateFormat;
- import java.util.*;
- /**
- * HttpsClient类
- * @author lujunjie
- * @date 2018/03/01
- */
- public class HttpsClient {
- /**
- * GET请求方式
- */
- public static final String METHOD_GET = "GET";
- /**
- * POST请求方式
- */
- public static final String METHOD_POST = "POST";
- /**
- * 连接超时时间
- */
- private static Integer CONNECTION_TIMEOUT = WxConfig.connectionTimeout;
- /**
- * 请求超时时间
- */
- private static Integer READ_TIMEOUT = WxConfig.readTimeout;
- /**
- * 发起https请求
- *
- * @param requestUrl 请求地址
- * @param requestMethod 请求方式(Get或者post)
- * @param postData 提交数据
- * @return JSONObject
- */
- public static JSONObject httpsRequestReturnJSONObject(String requestUrl, String requestMethod, String postData) throws Exception {
- JSONObject jsonObject = JSONObject.parseObject(HttpsClient.httpsRequestReturnString(requestUrl, requestMethod, postData));
- System.out.println("jsonObjectDate: " + jsonObject);
- return jsonObject;
- }
- /**
- * 发起https请求
- *
- * @param requestUrl 请求地址
- * @param requestMethod 请求方式(Get或者post)
- * @param postData 提交数据
- * @return String
- */
- public static String httpsRequestReturnString(String requestUrl, String requestMethod, String postData) throws Exception {
- String 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/x-www-form-urlencoded");
- //设置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 = WxUtil.getStreamString(httpsUrlConnection.getInputStream());
- } catch (Exception e) {
- throw new Exception();
- } finally {
- if (httpsUrlConnection != null) {
- // 关闭连接
- httpsUrlConnection.disconnect();
- }
- }
- return response;
- }
- public static void get(String url, Map<String, String> params) {
- CloseableHttpClient httpClient = null;
- HttpGet httpGet = null;
- try {
- httpClient = HttpClients.createDefault();
- RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
- String ps = "";
- for (String pKey : params.keySet()) {
- if (!"".equals(ps)) {
- ps = ps + "&";
- }
- ps = pKey + "=" + params.get(pKey);
- }
- if (!"".equals(ps)) {
- url = url + "?" + ps;
- }
- httpGet = new HttpGet(url);
- httpGet.setConfig(requestConfig);
- CloseableHttpResponse response = httpClient.execute(httpGet);
- HttpEntity httpEntity = response.getEntity();
- System.out.println(EntityUtils.toString(httpEntity, "utf-8"));
- } catch (ClientProtocolException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- if (httpGet != null) {
- httpGet.releaseConnection();
- }
- if (httpClient != null) {
- httpClient.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- public static String get(String strURL) throws Exception {
- URL url = new URL(strURL);
- HttpURLConnection httpConn = (HttpURLConnection)
- url.openConnection();
- httpConn.setRequestMethod("GET");
- httpConn.connect();
- System.out.println("bbb: " + httpConn.getResponseCode());
- BufferedReader reader = new BufferedReader(new InputStreamReader(
- httpConn.getInputStream(), "utf-8"));
- String line;
- StringBuffer buffer = new StringBuffer();
- while ((line = reader.readLine()) != null) {
- buffer.append(line);
- }
- reader.close();
- httpConn.disconnect();
- return buffer.toString();
- }
- /**
- * 发送 post请求
- *
- * @param
- * @param
- */
- public static void post(String url, Map<String, String> params) {
- CloseableHttpClient httpClient = null;
- HttpPost httpPost = null;
- try {
- httpClient = HttpClients.createDefault();
- RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(20000).setConnectTimeout(20000).build();
- httpPost = new HttpPost(url);
- httpPost.setConfig(requestConfig);
- List<NameValuePair> ps = new ArrayList<NameValuePair>();
- for (String pKey : params.keySet()) {
- ps.add(new BasicNameValuePair(pKey, params.get(pKey)));
- }
- httpPost.setEntity(new UrlEncodedFormEntity(ps));
- CloseableHttpResponse response = httpClient.execute(httpPost);
- HttpEntity httpEntity = response.getEntity();
- System.out.println(EntityUtils.toString(httpEntity, "utf-8"));
- } catch (ClientProtocolException e) {
- e.printStackTrace();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- if (httpPost != null) {
- httpPost.releaseConnection();
- }
- if (httpClient != null) {
- httpClient.close();
- }
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- //url表示请求链接,param表示json格式的请求参数 //自定义菜单创建访问方式
- public static String sendPost(String url, String param) {
- PrintWriter out = null;
- BufferedReader in = null;
- String result = "";
- try {
- URL realUrl = new URL(url);
- // 打开和URL之间的连接
- URLConnection conn = realUrl.openConnection();
- // 设置通用的请求属性 注意Authorization生成
- // conn.setRequestProperty("Content-Type",
- // "application/x-www-form-urlencoded");
- // 发送POST请求必须设置如下两行
- conn.setDoOutput(true);
- conn.setDoInput(true);
- // 获取URLConnection对象对应的输出流
- out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8"));
- // 发送请求参数
- out.print("&" + param);
- // flush输出流的缓冲
- out.flush();
- // 定义BufferedReader输入流来读取URL的响应
- in = new BufferedReader(
- new InputStreamReader(conn.getInputStream(), "utf-8"));
- String line;
- while ((line = in.readLine()) != null) {
- result += line;
- }
- } catch (Exception e) {
- System.out.println("发送 请求出现异常!" + e);
- e.printStackTrace();
- }
- // 使用finally块来关闭输出流、输入流
- finally {
- try {
- if (out != null) {
- out.close();
- }
- if (in != null) {
- in.close();
- }
- } catch (IOException ex) {
- ex.printStackTrace();
- }
- }
- return result;
- }
- //url表示请求链接,param表示json格式的请求参数 //自定义菜单创建访问方式
- public static String sendPost2(String url, String param) {
- PrintWriter out = null;
- BufferedReader in = null;
- String result = "";
- try {
- HttpsURLConnection httpsUrlConnection = null;
- //创建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 realUrl = new URL(url);
- // 创建HttpsURLConnection对象,并设置其SSLSocketFactory对象,
- // 打开和URL之间的连接
- httpsUrlConnection = (HttpsURLConnection) realUrl.openConnection();
- //设置ssl证书
- httpsUrlConnection.setSSLSocketFactory(ssf);
- // 设置通用的请求属性 注意Authorization生成
- // conn.setRequestProperty("Content-Type",
- // "application/x-www-form-urlencoded");
- // 发送POST请求必须设置如下两行
- httpsUrlConnection.setRequestMethod("POST");
- httpsUrlConnection.setDoOutput(true);
- httpsUrlConnection.setDoInput(true);
- // 获取URLConnection对象对应的输出流
- out = new PrintWriter(new OutputStreamWriter(httpsUrlConnection.getOutputStream(), "utf-8"));
- // 发送请求参数
- out.print("&" + param);
- // flush输出流的缓冲
- out.flush();
- if (httpsUrlConnection.getResponseCode() == 200) {
- // 定义BufferedReader输入流来读取URL的响应
- in = new BufferedReader(
- new InputStreamReader(httpsUrlConnection.getInputStream(), "utf-8"));
- String line;
- while ((line = in.readLine()) != null) {
- result += line;
- }
- } else {
- result = "获取输入流异常!";
- }
- } catch (Exception e) {
- System.out.println("发送 请求出现异常!" + e);
- e.printStackTrace();
- }
- // 使用finally块来关闭输出流、输入流
- finally {
- try {
- if (out != null) {
- out.close();
- }
- if (in != null) {
- in.close();
- }
- } catch (IOException ex) {
- ex.printStackTrace();
- }
- }
- return result;
- }
- public static String sendPost3(String url, String param) {
- PrintWriter out = null;
- BufferedReader in = null;
- String result = "";
- try {
- URL realUrl = new URL(url);
- // 打开和URL之间的连接
- URLConnection conn = realUrl.openConnection();
- // 设置通用的请求属性 注意Authorization生成
- // conn.setRequestProperty("Content-Type",
- // "application/x-www-form-urlencoded");
- // 发送POST请求必须设置如下两行
- conn.setDoOutput(true);
- conn.setDoInput(true);
- // 获取URLConnection对象对应的输出流
- out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8"));
- // 发送请求参数
- out.print(param);
- // flush输出流的缓冲
- out.flush();
- // 定义BufferedReader输入流来读取URL的响应
- in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
- String line;
- while ((line = in.readLine()) != null) {
- result += line;
- }
- } catch (Exception e) {
- System.out.println("发送 POST 请求出现异常!" + e);
- e.printStackTrace();
- }
- // 使用finally块来关闭输出流、输入流
- finally {
- try {
- if (out != null) {
- out.close();
- }
- if (in != null) {
- in.close();
- }
- } catch (IOException ex) {
- ex.printStackTrace();
- }
- }
- return result;
- }
- public static String sendJson(String request_url, JSONObject json) {
- OutputStreamWriter out = null;
- InputStream is = null;
- String result = "";
- try {
- URL url = new URL(request_url);// 创建连接
- HttpURLConnection connection = (HttpURLConnection) url.openConnection();
- connection.setDoOutput(true);
- connection.setDoInput(true);
- connection.setUseCaches(false);
- connection.setInstanceFollowRedirects(true);
- connection.setRequestMethod("POST"); // 设置请求方式
- // 设置接收数据的格式
- connection.setRequestProperty("Accept", "application/json");
- // 设置发送数据的格式
- connection.setRequestProperty("Content-Type", "application/json");
- connection.connect();
- out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
- out.append(json.toString());
- out.flush();
- out.close();
- // 读取响应
- is = connection.getInputStream();
- int length = (int) connection.getContentLength();// 获取长度
- if (length != -1) {
- byte[] data = new byte[length];
- byte[] temp = new byte[512];
- int readLen = 0;
- int destPos = 0;
- while ((readLen = is.read(temp)) > 0) {
- System.arraycopy(temp, 0, data, destPos, readLen);
- destPos += readLen;
- }
- result = new String(data, "UTF-8"); // utf-8编码
- System.out.println("主机返回:" + result);
- }
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- is.close();
- out.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return result;
- }
- public static String sendJson2(String request_url, JSONObject json) {
- OutputStreamWriter out = null;
- InputStream is = null;
- String result = "";
- try {
- URL url = new URL(request_url);// 创建连接
- HttpURLConnection connection = (HttpURLConnection) url.openConnection();
- connection.setDoOutput(true);
- connection.setDoInput(true);
- connection.setUseCaches(false);
- connection.setInstanceFollowRedirects(true);
- connection.setRequestMethod("POST"); // 设置请求方式
- // 设置接收数据的格式
- connection.setRequestProperty("Accept", "application/json");
- // 设置发送数据的格式
- connection.setRequestProperty("Content-Type", "application/json");
- connection.connect();
- out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8");
- out.append(json.toString());
- out.flush();
- out.close();
- // 读取响应
- is = connection.getInputStream();
- BufferedReader in = new BufferedReader(new InputStreamReader(is));
- result = in.readLine();
- } catch (IOException e) {
- e.printStackTrace();
- } finally {
- try {
- is.close();
- out.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- return result;
- }
- // public static void main(String[] args) throws Exception {
- // JSONObject json = new JSONObject();
- // String ukey = "6VMZEC5C6HZM7EO8";
- // JSONObject datas = new JSONObject();
- // datas.put("car_number", "赣555555");
- // datas.put("begin_time", 1630800000);
- // datas.put("end_time", 1630918800);
- // datas.put("mobile", "15399990000");
- // // 生成带签名的字符串并使用MD5生成签名,然后转大写
- // String sign = datas.toJSONString()+"key="+ukey;
- // sign = CreateSign1.MD5(sign).toUpperCase();
- // json.put("service_name", "visitor_sync");
- // json.put("sign", sign);
- // json.put("park_id", "10033845");
- // json.put("data", datas);
- // String msg = sendJson2("http://istparking.sciseetech.com/public/visitor/do", json);
- // System.out.println(msg);
- // }
- // public static void main(String[] args) {
- // JSONObject json = new JSONObject();
- // String ukey = "6VMZEC5C6HZM7EO8";
- // JSONObject datas = new JSONObject();
- // // 1新增 2编辑 3删除
- // datas.put("operate_type", "1");
- // // 白名单编号(收费系统唯一编号)
- // datas.put("card_id", "20210810556");
- // datas.put("car_number", "冀A111118");
- // datas.put("mobile", "15399990000");
- // // 是否长期类型1是,0否,默认0
- // datas.put("end_type", "0");
- // datas.put("b_time", 1630800000);
- // datas.put("e_time", 1630918800);
- // // 生成带签名的字符串并使用MD5生成签名,然后转大写
- // String sign = datas.toJSONString()+"key="+ukey;
- // sign = CreateSign1.MD5(sign).toUpperCase();
- // json.put("service_name", "white_vip");
- // json.put("sign", sign);
- // json.put("park_id", "10033845");
- // json.put("data", datas);
- // String msg = sendJson2("http://istparking.sciseetech.com/public/vip/white", json);
- // Gson gson=new Gson();
- // HashMap<String, String> userMoney = gson.fromJson(msg.toString(), new TypeToken<HashMap<String, String>>(){}.getType());
- // System.out.println(msg);
- // }
- // public static void main(String[] args) throws Exception {
- // JSONObject data = new JSONObject();
- // data.put("carNumber", "赣555555");
- // data.put("parkId", "10033845");
- // data.put("type", "2"); // 进出类别 1进、2出
- // data.put("recordTime", "2021-11-10 17:02:25");
- // String msg = sendJson2("https://chtech.ncjti.edu.cn/bigdata-api/api/intoAndOut/carIntoAndOutRecordUpload", data);
- // System.out.println(msg);
- // }
- public static void main(String[] args) {
- String msg = HttpsClient.sendPost(
- "https://open.wecard.qq.com/cgi-bin/oauth2/token?app_key="+
- "48103AB41FFBC5FE&app_secret=5B7FB4D3CC243695EED3693044D0FC54&grant_type=client_credentials&scope=base&ocode=1015730314", "");
- Gson gson=new Gson();
- HashMap<String, String> userMap = gson.fromJson(msg.toString(), new TypeToken<HashMap<String, String>>(){}.getType());
- String token = userMap.get("access_token");
- System.out.println(token);
- JSONObject data = new JSONObject();
- ArrayList<String> as = new ArrayList<>();
- as.add("REG4377000007");
- String json = JSONObject.toJSONString(as);
- data.put("cards", json);
- data.put("title", "访客预约结果");
- data.put("content", "预约成功"); // 进出类别 1进、2出
- data.put("sender", "保卫处");
- String msg2 = sendJson2("https://open.wecard.qq.com/cgi-bin/notice/send?access_token="+token, data);
- System.out.println(msg2);
- }
- }
|