- package com.qgproxy;
- import java.io.ByteArrayOutputStream;
- import java.io.InputStream;
- import java.net.Authenticator;
- import java.net.HttpURLConnection;
- import java.net.InetSocketAddress;
- import java.net.PasswordAuthentication;
- import java.net.Proxy;
- import java.net.URL;
- class QGProxyAuthenticator extends Authenticator {
- private String user, password;
- public QGProxyAuthenticator(String user, String password) {
- this.user = user;
- this.password = password;
- }
- protected PasswordAuthentication getPasswordAuthentication() {
- return new PasswordAuthentication(user, password.toCharArray());
- }
- }
- class QGProxy {
- public static void main(String args[]) {
- // 如果您的本地jdk版本在Java 8 Update 111以上,需要增加以下代码
- // System.setProperty("jdk.http.auth.tunneling.disabledSchemes", "false");
- // System.setProperty("jdk.http.auth.proxying.disabledSchemes", "false");
- String targetUrl = "https://ip.hahado.cn/api/index?ip=&type=0";
- String proxyIp = "您的代理IP";
- int proxyPort = 端口号;
- String authKey = "请改成您的Key";
- String password = "请改成您的AuthPwd";
- try {
- URL url = new URL(targetUrl);
- Authenticator.setDefault(new QGProxyAuthenticator(authKey, password));
- InetSocketAddress socketAddress = new InetSocketAddress(proxyIp, proxyPort);
- Proxy proxy = new Proxy(Proxy.Type.HTTP, socketAddress);
- HttpURLConnection connection = (HttpURLConnection) url.openConnection(proxy);
- byte[] response = readStream(connection.getInputStream());
- System.out.println(new String(response));
- } catch (Exception e) {
- System.out.println(e.getLocalizedMessage());
- }
- }
- public static byte[] readStream(InputStream inStream) throws Exception {
- ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
- byte[] buffer = new byte[1024];
- int len = -1;
- while ((len = inStream.read(buffer)) != -1) {
- outSteam.write(buffer, 0, len);
- }
- outSteam.close();
- inStream.close();
- return outSteam.toByteArray();
- }
- }
嵌入代码使用,即可实现使用隧道来进行
标签:java,Java,String,示例,代码,import,new,net,password From: https://blog.51cto.com/u_15822686/7030984