OkHttp proxy settings

后端 未结 3 2046
情歌与酒
情歌与酒 2021-02-07 00:14

I have to setup a proxy to send a JSON using POST, using proxyHost and proxyPort.

public static final MediaType JSON = MediaType.parse(\"application/json; charse         


        
相关标签:
3条回答
  • 2021-02-07 00:21

    SOCKS5 Auth example

    I think it's the easiest working soulution. But it seems to me that it can be not 100% safe. I took this code from this code from here and modified it because my proxy's RequestorType is SERVER. Actually, java has a strange api for proxies, you should to set auth for proxy through system env ( you can see it from the same link)

    final int proxyPort = 1080; //your proxy port
    final String proxyHost = "your proxy host";
    final String username = "proxy username";
    final String password = "proxy password";
    
    InetSocketAddress proxyAddr = new InetSocketAddress(proxyHost, proxyPort);
    Proxy proxy = new Proxy(Proxy.Type.SOCKS, proxyAddr);
    
    Authenticator.setDefault(new Authenticator() {
      @Override
      protected PasswordAuthentication getPasswordAuthentication() {
        if (getRequestingHost().equalsIgnoreCase(proxyHost)) {
          if (proxyPort == getRequestingPort()) {
            return new PasswordAuthentication(username, password.toCharArray());
          }
        }
        return null;
      }
    });
    
    
    OkHttpClient client = new OkHttpClient.Builder()
            .proxy(proxy)
            .build();
    
    0 讨论(0)
  • 2021-02-07 00:30

    Found the solution:

      OkHttpClient client = new OkHttpClient.Builder().proxy(proxyTest).build();
    

    If we use the builder to input the proxy, it will work like a charm =D

    0 讨论(0)
  • 2021-02-07 00:32

    okhttp version:3.11.0. SOCKS proxy example

    String hostname = "localhost"/*127.0.0.1*/;
    int port = 1080;
    Proxy proxy = new Proxy(Proxy.Type.SOCKS,
            new InetSocketAddress(hostname, port));
    
    OkHttpClient client = new OkHttpClient.Builder()
            .proxy(proxy)
            .build();
    
    0 讨论(0)
提交回复
热议问题