import java.io.IOException; import java.io.InputStream; import java.net.*; public class NetProxy { public static void main(String[] args) throws IOException { //設置請求訪問的地址 URL url = new URL("https://www.baidu.com/"); //設置代理 , 端口是你自己使用軟件代理的本地出口,socks和http代理的端口 InetSocketAddress address = new InetSocketAddress("127.0.0.1",1080); Proxy proxy = new Proxy(Proxy.Type.HTTP, address); // http 代理 URLConnection connection = url.openConnection(proxy); //此處是瀏覽器的請求頭. 一般是為了防止對面設置的反爬 connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/61.0.3163.100 Safari/537.36)"); connection.connect(); //連接獲取數據流 InputStream inputStream = connection.getInputStream(); //轉化數據流變數據本 StringBuilder sb1 = new StringBuilder(); byte[] buffer = new byte[1024]; int len; while((len = inputStream.read(buffer)) != -1) { sb1.append(new String(buffer, 0, len, "UTF-8")); } //輸出文本至屏幕 System.out.println(sb1); } }
我是設置的系統代理, 而非直接訪問的遠程代理,這點注意一下 .其實就相當於端口轉發而已.
Chrome獲取 User-Agent 步驟:
1. 打開 百度首頁 , 按F12
2.在控制台 , 輸入 javascript:alert(navigator.userAgent)