java:exemple:proxyetauthentification

Connection à travers un Proxy en utilisant un programme Java

Exemple:

import java.io.DataInputStream;
import java.io.IOException;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.PasswordAuthentication;
import java.net.URL;
 
public class ProxyR {
	public static void main(String[] args) throws Exception {
		System.out.println(isValidProxyAccount("proxy.host","proxy.port"));
	}
 
 
	public static boolean isValidProxyAccount(String proxyServer, String proxyPort) throws IOException {
		String go_url = new String("http://gwadanina.net");
		boolean isValide = true;
 
		try {
			URL url = new URL(vURL);
 
			System.getProperties().put("proxySet", "true");
			System.getProperties().put("http.proxyHost", proxyServer);
			System.getProperties().put("http.proxyPort", proxyPort);
 
			HttpURLConnection vopenConnection = (HttpURLConnection) url.openConnection();
			Authenticator.setDefault(new MyAuthenticator());
 
			int vCodeRetour = vopenConnection.getResponseCode();
			String vMessageRetour = vopenConnection.getResponseMessage();
 
			System.out.println("code::" + vCodeRetour);
			System.out.println("MessageRetour::" + vMessageRetour);
 
                        DataInputStream din = new DataInputStream(vopenConnection.getInputStream());
			StringBuffer sb = new StringBuffer();
 
			String line = null;
			while((line=din.readLine()) != null){
				sb.append(line+"\n");
			}
			System.out.println(sb.toString());
 
			System.getProperties().put("proxySet", "false");
			System.getProperties().remove("http.proxyHost");
			System.getProperties().remove("http.proxyPort");
 
			vopenConnection.disconnect();
 
			if (vCodeRetour != 200) {
				isValide = false;
				throw new IOException("Failed to connect to proxy: " + vMessageRetour);
			}
		} catch (Exception ex) {
			System.out.println(ex.getMessage());
			throw new IOException(ex.getMessage());
		}
 
		return isValide;
	}
 
}
 
class MyAuthenticator extends Authenticator{
	protected PasswordAuthentication getPasswordAuthentication(){
		return new PasswordAuthentication("login", "password".toCharArray());
	}
}
  • java/exemple/proxyetauthentification.txt
  • Dernière modification: 2018/10/13 14:59
  • (modification externe)