Proxy server and Proxy Authentication to URL connection

Total Views : 156
Zoom In Zoom Out Read Later Print

This code will help you to know how you can use proxy server for a URL connection in java.

ProxyAndAuth.java

package com.prodevsblog.how_to.network.url;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.*;

public class ProxyAndAuth {
    public static void main(String[] args){
        InputStream is = null;
        FileOutputStream fos = null;
        try {
            URL url = new URL("https://prodevsblog.com/demo/blog_68_1.png");

            System.out.println("Reading..." + url);

            Authenticator.setDefault(new ProxyAuthenticator("username", "password"));

            SocketAddress addr = new InetSocketAddress("your proxyserver ip address", 80);
            Proxy proxy = new Proxy(Proxy.Type.HTTP, addr);

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

            is = conn.getInputStream();

            // Get File Name
            String[] urlParts = url.getPath().split("/");
            String filename = "d:/" + urlParts[urlParts.length - 1];

            fos = new FileOutputStream(filename);

            byte[] readData = new byte[1024];

            int i = is.read(readData);

            while (i != -1) {
                fos.write(readData, 0, i);
                i = is.read(readData);
            }

            System.out.println("Created file: " + filename);
            System.out.println("Completed");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

class ProxyAuthenticator extends Authenticator {
    private String userName, password;

    public ProxyAuthenticator(String userName, String password) {
        this.userName = userName;
        this.password = password;
    }

    protected PasswordAuthentication getPasswordAuthentication() {
        return new PasswordAuthentication(userName, password.toCharArray());
    }
}

Output of the code.

Output:

Reading...https://prodevsblog.com/demo/blog_68_1.png
Created file: d:/blog_68_1.png
Completed

Process finished with exit code 0

See More

Latest Photos