|
|
@@ -0,0 +1,73 @@
|
|
|
+package com.vber.common.utils.http;
|
|
|
+
|
|
|
+import cn.hutool.json.JSONUtil;
|
|
|
+
|
|
|
+import java.io.BufferedReader;
|
|
|
+import java.io.InputStreamReader;
|
|
|
+import java.io.OutputStream;
|
|
|
+import java.io.OutputStreamWriter;
|
|
|
+import java.net.HttpURLConnection;
|
|
|
+import java.net.URL;
|
|
|
+
|
|
|
+public class HttpHelper {
|
|
|
+
|
|
|
+ public static String sendGetRequest(String url) {
|
|
|
+ StringBuilder response = new StringBuilder();
|
|
|
+ try {
|
|
|
+ URL obj = new URL(url);
|
|
|
+ HttpURLConnection con = (HttpURLConnection) obj.openConnection();
|
|
|
+ con.setRequestMethod("GET");
|
|
|
+
|
|
|
+ BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
|
|
|
+ String inputLine;
|
|
|
+ while ((inputLine = in.readLine()) != null) {
|
|
|
+ response.append(inputLine);
|
|
|
+ }
|
|
|
+ in.close();
|
|
|
+ con.disconnect();
|
|
|
+ } catch (Exception e) {
|
|
|
+ e.printStackTrace();
|
|
|
+ }
|
|
|
+ return response.toString();
|
|
|
+ }
|
|
|
+
|
|
|
+ public static String sendPostRequest(String url, String data) {
|
|
|
+ StringBuilder response = new StringBuilder();
|
|
|
+ try {
|
|
|
+ URL obj = new URL(url);
|
|
|
+ HttpURLConnection con = (HttpURLConnection) obj.openConnection();
|
|
|
+ con.setRequestMethod("POST");
|
|
|
+ con.setDoOutput(true);
|
|
|
+ con.setRequestProperty("Content-Type", "application/json");
|
|
|
+ OutputStream os = con.getOutputStream();
|
|
|
+ OutputStreamWriter osw = new OutputStreamWriter(os);
|
|
|
+ osw.write(data);
|
|
|
+ osw.flush();
|
|
|
+ osw.close();
|
|
|
+
|
|
|
+ BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
|
|
|
+ String inputLine;
|
|
|
+ while ((inputLine = in.readLine()) != null) {
|
|
|
+ response.append(inputLine);
|
|
|
+ }
|
|
|
+ in.close();
|
|
|
+ os.close();
|
|
|
+ con.disconnect();
|
|
|
+ } catch (Exception e) {
|
|
|
+ e.printStackTrace();
|
|
|
+ }
|
|
|
+ return response.toString();
|
|
|
+ }
|
|
|
+
|
|
|
+ public static <T> T Post(String url, Object data, Class<T> clazz) {
|
|
|
+ String dataStr = JSONUtil.toJsonStr(data);
|
|
|
+ String response = sendPostRequest(url, dataStr);
|
|
|
+ try {
|
|
|
+ return JSONUtil.toBean(response, clazz);
|
|
|
+ } catch (Exception e) {
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+
|
|
|
+}
|