java使用代理访问https://
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)