|
|
@@ -29,6 +29,72 @@ public class HttpsUtils {
|
|
|
* @param outputStr 提交的数据
|
|
|
* @return json字符串
|
|
|
*/
|
|
|
+ public static JSONObject doRequest(String requestUrl, String requestMethod, String outputStr) {
|
|
|
+ StringBuffer buffer = new StringBuffer();
|
|
|
+ JSONObject jsonObject;
|
|
|
+ try {
|
|
|
+ // 创建SSLContext对象,并使用我们制定的信任管理器初始化
|
|
|
+ TrustManager[] tm = {new MyX509TrustManager()};
|
|
|
+ SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
|
|
|
+ sslContext.init(null, tm, new java.security.SecureRandom());
|
|
|
+ // 从上述SSLContext对象中得到SSLSocketFactory对象
|
|
|
+ SSLSocketFactory ssf = sslContext.getSocketFactory();
|
|
|
+
|
|
|
+ URL url = new URL(requestUrl);
|
|
|
+ HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
|
|
|
+ httpUrlConn.setSSLSocketFactory(ssf);
|
|
|
+
|
|
|
+ httpUrlConn.setDoOutput(true);
|
|
|
+ httpUrlConn.setDoInput(true);
|
|
|
+ httpUrlConn.setUseCaches(false);
|
|
|
+ // 设置请求方式(GET/POST)
|
|
|
+ httpUrlConn.setRequestMethod(requestMethod);
|
|
|
+
|
|
|
+ if ("GET".equalsIgnoreCase(requestMethod)) {
|
|
|
+ httpUrlConn.connect();
|
|
|
+ }
|
|
|
+
|
|
|
+ //当outputStr不为null时向输出流写数据
|
|
|
+ if (null != outputStr) {
|
|
|
+ OutputStream outputStream = httpUrlConn.getOutputStream();
|
|
|
+ // 注意编码格式,防止中文乱码
|
|
|
+ outputStream.write(outputStr.getBytes("UTF-8"));
|
|
|
+ outputStream.close();
|
|
|
+ }
|
|
|
+
|
|
|
+ // 将返回的输入流转换成字符串
|
|
|
+ InputStream inputStream = httpUrlConn.getInputStream();
|
|
|
+ InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
|
|
|
+ BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
|
|
|
+
|
|
|
+ String str = null;
|
|
|
+ while ((str = bufferedReader.readLine()) != null) {
|
|
|
+ buffer.append(str);
|
|
|
+ }
|
|
|
+
|
|
|
+ // 释放资源
|
|
|
+ bufferedReader.close();
|
|
|
+ inputStreamReader.close();
|
|
|
+ inputStream.close();
|
|
|
+ httpUrlConn.disconnect();
|
|
|
+ log.debug("https buffer:" + buffer.toString());
|
|
|
+ } catch (ConnectException ce) {
|
|
|
+ log.error("server connection timed out");
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.error(e.getMessage());
|
|
|
+ }
|
|
|
+ jsonObject = JSONObject.parseObject(buffer.toString());
|
|
|
+ return jsonObject;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 发起https请求并获取结果
|
|
|
+ *
|
|
|
+ * @param requestUrl 请求地址
|
|
|
+ * @param requestMethod 请求方式(GET、post)
|
|
|
+ * @param outputStr 提交的数据
|
|
|
+ * @return json字符串
|
|
|
+ */
|
|
|
public static JSONObject doRequest(String requestUrl, String requestMethod, String outputStr, String token) {
|
|
|
StringBuffer buffer = new StringBuffer();
|
|
|
JSONObject jsonObject;
|