Browse Source

abstract out httputils

fengchang 1 year ago
parent
commit
aaaa34be4f

+ 3 - 36
hichina-main-back/src/main/java/com/hichina/main/back/hichinamainback/controller/DemoController.java

@@ -2,18 +2,13 @@ package com.hichina.main.back.hichinamainback.controller;
 
 import com.google.gson.JsonObject;
 import com.google.gson.JsonParser;
+import com.hichina.main.back.hichinamainback.utils.HttpUtils;
 import com.hichina.main.back.hichinamainback.utils.RedisUtil;
 import com.hichina.main.back.hichinamainback.utils.WxPayUtil;
-import jakarta.servlet.http.Cookie;
-import jakarta.servlet.http.HttpServletRequest;
-import jakarta.servlet.http.HttpServletResponse;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.GetMapping;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RestController;
-import org.springframework.web.context.request.RequestContextHolder;
-import org.springframework.web.context.request.ServletRequestAttributes;
-
 import java.io.BufferedReader;
 import java.io.IOException;
 import java.io.InputStreamReader;
@@ -44,38 +39,10 @@ public class DemoController {
         int proxyPort = 1083;
 
         // Define the target URL
-        String targetUrl = "https://graph.facebook.com/v14.0/me?access_token=EAAOIMZBkz7HoBABqSIYZClDV3rAVoK13PWFLhV3cxI3ZAamWQpSjdmv75QWWtLKv3g257ZAoMUetnIxZCNM6A6sP7qWP2khPv1SQOQqo6TjZBTIHZCkg7kkIeDMlcOKqaPSb35oF1S8prev7uRzLsCg8CYY8shdpMZBSFZAu0OekgC9rZCpQtW59YOB7LAjJkEcNsPMPyAuDF6uw6jrVmCNBeW";
-
-        // Create a Proxy object with the proxy server details
-        Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(proxyHost, proxyPort));
-
-        // Create a URL object with the target URL
-        URL url = new URL(targetUrl);
-
-        // Open a connection to the URL using the proxy
-        HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);
-
-        connection.setRequestMethod("GET");
-        StringBuilder responseBuilder = new StringBuilder();
-        try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
-            String line;
-            while ((line = reader.readLine()) != null) {
-                responseBuilder.append(line);
-            }
-        }
-        String response = responseBuilder.toString();
-        // Set the request method (GET, POST, etc.)
-//        connection.setRequestMethod("GET");
-
-        // Get the response code
-        int responseCode = connection.getResponseCode();
-        System.out.println("Response Code: " + responseCode);
+        String targetUrl = "https://graph.facebook.com/v14.0/me?access_token=EAAOIMZBkz7HoBAGkAuxiCExK50z7KBaIePyqmoHtzy49WWkO5y1GvkcvSNZBv7nEZAjNFv9DwZBecOEImptxcGmThXkShS8zL7j3tK0YkcHaTgTQeZBvXuRVTL35Juq5ZCD96pMOTIZBdADUtoPgMN14WgiipQnWk3saICPQKNmeUe9Xgj3VwB4YDwTarD6LWS81oX4n6ztbYqvLwmfSuqA";
 
-        // Read the response content
-        // ...
 
-        // Close the connection
-        connection.disconnect();
+        String response = HttpUtils.sendToWithProxy(targetUrl, proxyHost, proxyPort);
 
         JsonParser jsonParser = new JsonParser();
         JsonObject jsonResponse = jsonParser.parse(response).getAsJsonObject();

+ 3 - 26
hichina-main-back/src/main/java/com/hichina/main/back/hichinamainback/utils/FacebookAccessTokenValidator.java

@@ -7,11 +7,7 @@ import org.slf4j.LoggerFactory;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.core.env.Environment;
 import org.springframework.stereotype.Component;
-
-import java.io.BufferedReader;
 import java.io.IOException;
-import java.io.InputStreamReader;
-import java.net.*;
 
 @Component
 public class FacebookAccessTokenValidator {
@@ -29,39 +25,20 @@ public class FacebookAccessTokenValidator {
     public boolean validateAccessToken(String accessToken) {
         // Define the proxy server details
         String proxyHost = "127.0.0.1";
-        System.setProperty("https.protocols", "TLSv1.2");
 
         int proxyPort = Integer.parseInt(env.getProperty("gfw.proxy.port"));
         // Define the target URL
         String targetUrl = GRAPH_API_URL+accessToken;
         // Create a Proxy object with the proxy server details
-        Proxy proxy = new Proxy(Proxy.Type.SOCKS, new InetSocketAddress(proxyHost, proxyPort));
-        // Create a URL object with the target URL
-        // Open a connection to the URL using the proxy
-        HttpURLConnection connection = null;
+
         try {
-            URL url = new URL(targetUrl);
-            System.setProperty("https.protocols", "TLSv1.2");
-            connection = (HttpURLConnection) url.openConnection(proxy);
-            connection.setRequestMethod("GET");
-            StringBuilder responseBuilder = new StringBuilder();
-            try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
-                String line;
-                while ((line = reader.readLine()) != null) {
-                    responseBuilder.append(line);
-                }
-            }
-            String response = responseBuilder.toString();
-            int responseCode = connection.getResponseCode();
-            System.out.println("Response Code: " + responseCode);
+            String response = HttpUtils.sendToWithProxy(targetUrl, proxyHost, proxyPort);
             JsonParser jsonParser = new JsonParser();
             JsonObject jsonResponse = jsonParser.parse(response).getAsJsonObject();
             return jsonResponse.has("id");
         } catch (IOException e) {
-            LOG.error("===exception in http request: "+e.getMessage());
+            LOG.error("===didn't validate succeed"+e.getMessage());
             return false;
-        } finally {
-            connection.disconnect();
         }
     }
 }

+ 77 - 0
hichina-main-back/src/main/java/com/hichina/main/back/hichinamainback/utils/HttpUtils.java

@@ -0,0 +1,77 @@
+package com.hichina.main.back.hichinamainback.utils;
+
+import org.apache.http.HttpEntity;
+import org.apache.http.HttpHost;
+import org.apache.http.client.ClientProtocolException;
+import org.apache.http.client.methods.CloseableHttpResponse;
+import org.apache.http.client.methods.HttpGet;
+import org.apache.http.client.protocol.HttpClientContext;
+import org.apache.http.config.Registry;
+import org.apache.http.config.RegistryBuilder;
+import org.apache.http.conn.socket.ConnectionSocketFactory;
+import org.apache.http.conn.socket.PlainConnectionSocketFactory;
+import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
+import org.apache.http.impl.client.CloseableHttpClient;
+import org.apache.http.impl.client.HttpClients;
+import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
+import org.apache.http.protocol.HttpContext;
+import org.apache.http.ssl.SSLContexts;
+import org.apache.http.util.EntityUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import javax.net.ssl.SSLContext;
+import java.io.IOException;
+import java.net.*;
+
+public class HttpUtils {
+    private static final Logger LOG = LoggerFactory.getLogger(HttpUtils.class);
+
+    public static String sendToWithProxy(String url, String proxyHost, Integer proxyPort) throws IOException {
+        System.setProperty("https.protocols", "TLSv1.2");
+        Registry<ConnectionSocketFactory> reg = RegistryBuilder.<ConnectionSocketFactory>create()
+                .register("http", PlainConnectionSocketFactory.INSTANCE)
+                .register("https", new MyConnectionSocketFactory(SSLContexts.createSystemDefault()))
+                .build();
+        PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager(reg);
+        CloseableHttpClient httpclient = HttpClients.custom()
+                .setConnectionManager(cm)
+                .build();
+        try {
+            InetSocketAddress socksaddr = new InetSocketAddress(proxyHost, proxyPort);
+            HttpClientContext context = HttpClientContext.create();
+            context.setAttribute("socks.address", socksaddr);
+
+//            HttpHost target = new HttpHost(proxyHost, proxyPort, "http");
+            HttpGet request = new HttpGet(url);
+
+//            LOG.info("Executing request " + request + " to " + target + " via SOCKS proxy " + socksaddr);
+            CloseableHttpResponse response = httpclient.execute(request, context);
+            try {
+                return new String(EntityUtils.toByteArray(response.getEntity()), "UTF-8");
+            } finally {
+                response.close();
+            }
+        }catch (ClientProtocolException e) {
+            LOG.error("===" + e.getMessage());
+        } catch (IOException e) {
+            LOG.error("===" + e.getMessage());
+        } finally {
+            httpclient.close();
+        }
+            return null;
+    }
+
+    static class MyConnectionSocketFactory extends SSLConnectionSocketFactory {
+
+        public MyConnectionSocketFactory(final SSLContext sslContext) {
+            super(sslContext);
+        }
+
+        @Override
+        public Socket createSocket(final HttpContext context) throws IOException {
+            InetSocketAddress socksaddr = (InetSocketAddress) context.getAttribute("socks.address");
+            Proxy proxy = new Proxy(Proxy.Type.SOCKS, socksaddr);
+            return new Socket(proxy);
+        }
+    }
+}