HTTP代码示例-JAVA

本文提供了四种Java实现HTTP代理的示例,包括HttpURLConnection、OkHttp、Jsoup和HttpClient,适用于通过HTTP代理进行网络请求的场景,涉及代理设置和认证处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

JAVA使用华科隧道HTTP代理示例,根据实际情况修改即可。

第一种、Java HttpURLConnection

      package com.hkproxy;
      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 HKProxyAuthenticatorg extends Authenticator {
        private String user, password;
        public HKProxyAuthenticator(String user, String password) {
          this.user = user;
          this.password = password;
        }
        protected PasswordAuthentication getPasswordAuthentication() {
          return new PasswordAuthentication(user, password.toCharArray());
        }
      }
      class HKProxy {
        public static void main(String args[]) {
          String targetUrl = "http://httpbin.org/ip";
          String proxyIp = "ip.hahado.cn";
          int proxyPort = 10080;
          String authKey = "username";
          String password = "password";
          try {
            URL url = new URL(targetUrl);
            Authenticator.setDefault(new HKProxyAuthenticator(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 okhttp

    package com.hkproxy;
    import okhttp3.*;
    import java.io.IOException;
    import java.net.InetSocketAddress;
    import java.net.Proxy;
    import java.util.concurrent.TimeUnit;
    public class HKProxy {
        final static String proxyIp = "ip.hahado.cn";
        final static Integer proxyPort = 10080;
        final static String authKey = "username";
        final static String password = "password";
        static OkHttpClient client;
        static {
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyIp, proxyPort));
            Authenticator proxyAuthenticator = (route, response) -> {
                String credential = Credentials.basic(authKey, password);
                return response.request().newBuilder().header("Proxy-Authorization", credential).build();
            };
            client = new OkHttpClient().newBuilder()
          .connectTimeout(10, TimeUnit.SECONDS)
          .readTimeout(10, TimeUnit.SECONDS)
          .proxy(proxy)
          .proxyAuthenticator(proxyAuthenticator)
          .connectionPool(new ConnectionPool(4, 2, TimeUnit.SECONDS))
          .build();
      }
        public static void main(String[] args) throws IOException {
            Request request = new Request.Builder().url("http://httpbin.org/ip").build();
            Response response = client.newCall(request).execute();
            System.out.println(response.body().string());
        }
    }

 

第三种、Java jsonp

    package com.hkproxy;
    import org.jsoup.Jsoup;
    import org.jsoup.nodes.Document;
    import java.io.IOException;
    import java.net.Authenticator;
    import java.net.InetSocketAddress;
    import java.net.PasswordAuthentication;
    import java.net.Proxy;
    public class HKProxy {
        final static String proxyIp = "ip.hahado.cn";
        final static Integer proxyPort = 10080;
        final static String authKey = "username";
        final static String password = "password";
        public static void main(String[] args) throws Exception {
            String targetUrl = "http://httpbin.org/ip";
            Authenticator.setDefault(new Authenticator() {
                public PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(authKey, password.toCharArray());
                }
        });
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyIp, proxyPort));
            try {
          Document doc = Jsoup.connect(url).timeout(10000).proxy(proxy).get();
          if (doc != null) {
            System.out.println(doc.body().html());
          }
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }

 

第四种、Java HttpClient

    package com.hkproxy;
    import org.apache.commons.httpclient.Credentials;
    import org.apache.commons.httpclient.HostConfiguration;
    import org.apache.commons.httpclient.HttpClient;
    import org.apache.commons.httpclient.HttpMethod;
    import org.apache.commons.httpclient.HttpStatus;
    import org.apache.commons.httpclient.UsernamePasswordCredentials;
    import org.apache.commons.httpclient.auth.AuthScope;
    import org.apache.commons.httpclient.methods.GetMethod;
    import java.io.IOException;
    public class HKProxy  {
      final static String proxyIp = "ip.hahado.cn";
      final static Integer proxyPort = 10080;
      final static String authKey = "username";
      final static String password = "password";
      public static void main(String[] args) {
        HttpClient client = new HttpClient();
        HttpMethod method = new GetMethod("http://httpbin.org/ip");
        HostConfiguration config = client.getHostConfiguration();
        config.setProxy(proxyIp, proxyPort);
        client.getParams().setAuthenticationPreemptive(true);
        Credentials credentials = new UsernamePasswordCredentials(authKey, password);
        AuthScope authScope = new AuthScope(proxyIp, proxyPort);
        client.getState().setProxyCredentials(authScope, credentials);
        try {
          client.executeMethod(method);
          if (method.getStatusCode() == HttpStatus.SC_OK) {
            System.out.println(method.getResponseBodyAsString());
          }
        } catch (IOException e) {
          e.printStackTrace();
        } finally {
          method.releaseConnection();
        }
      }
    }

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

super_ip_

你的打赏将是我的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值