Skip to content

Instantly share code, notes, and snippets.

@aldoKelvianto
Last active January 4, 2018 17:49
Show Gist options
  • Save aldoKelvianto/1e720e0092b08c9259523572e6674775 to your computer and use it in GitHub Desktop.
Save aldoKelvianto/1e720e0092b08c9259523572e6674775 to your computer and use it in GitHub Desktop.
HttpUrlConnection with Proxy (and authentication) for Android

How to enable your app connected to internet using proxy. Note: this only works http, still working on https.

private String fetchUsingProxy() throws IOException {
    URL url = new URL("http://www.google.com");

    Authenticator authenticator = new Authenticator() {
        @Override
        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication("aldo@yoursite.com", "password".toCharArray());
        }
    };

    Authenticator.setDefault(authenticator);

    Proxy proxy = new Proxy(Proxy.Type.HTTP,
            new InetSocketAddress("proxy.yoursite.com", 8080));

    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(proxy);

    InputStream in = urlConnection.getInputStream();
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    int bytesRead = 0;
    byte[] buffer = new byte[1024];
    out.write(buffer, 0, bytesRead);

    while((bytesRead = in.read(buffer)) > 0){
        out.write(buffer, 0, bytesRead);
    }

    out.close();
    out.flush();
    return out.toString();
}
@jamesajones
Copy link

Did you ever get https to work?

@sanpei3
Copy link

sanpei3 commented Nov 22, 2017

I reproduce this issue in our product. I reported this issue to Google Issue Tracker as below:
https://issuetracker.google.com/issues/69585854

If you still have this issue, please check start that issue.

And for your information, I already wrote that in that issue tracker, this issue related to okhttp which is used in Android OS internally.

Yours.

@alirezaashrafi
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment