package com.test.porxy; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.net.HttpURLConnection; import java.net.InetSocketAddress; import java.net.Proxy; import java.net.URL; import java.net.Proxy.Type; public class HttpAndHttpsProxy { /** * url:外網測試地址 param:請求報文 proxy:代理地址(內網IP地址:10.0.100.00) port :端口號(22) * **/ public static String HttpProxy(String url, String param, String proxy, int port) { HttpURLConnection httpConn = null; PrintWriter out = null; OutputStreamWriter out1 = null; BufferedReader in = null; String result = ""; BufferedReader reader = null; try { URL urlClient = new URL(url); System.out.println("請求的URL========:" + urlClient); // 創建代理 Proxy proxy1 = new Proxy(Type.HTTP, new InetSocketAddress(proxy, port)); // 設置代理 httpConn = (HttpURLConnection) urlClient.openConnection(proxy1); // 設置通用的請求屬性 httpConn.setRequestProperty("accept", "*/*"); httpConn.setRequestProperty("connection", "Keep-Alive"); httpConn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); // 發送POST請求必須設置如下兩行 httpConn.setDoOutput(true); httpConn.setDoInput(true); // 獲取URLConnection對象對應的輸出流 //使請求報文不中文亂碼 out1 = new OutputStreamWriter(httpConn.getOutputStream(), "utf-8"); out1.write(param); // 發送請求參數 // out.print(param); // flush輸出流的緩沖 out1.flush(); // 定義BufferedReader輸入流來讀取URL的響應 // in = new BufferedReader( // new InputStreamReader(httpConn.getInputStream())); //使返回的報文不中文亂碼 in = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "utf-8")); String line; while ((line = in.readLine()) != null) { result += line; } // 斷開連接 httpConn.disconnect(); System.out.println("====result====" + result); System.out.println("返回結果:" + httpConn.getResponseMessage()); } catch (Exception e) { e.printStackTrace(); } finally { try { if (reader != null) { reader.close(); } } catch (IOException e) { e.printStackTrace(); } try { if (in != null) { in.close(); } } catch (IOException e) { e.printStackTrace(); } try { if (out1 != null) { out1.close(); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return result; } public static void main(String[] args) { // 示例 HttpProxy("請求地址", "請求參數", "代理地址", 0); } }