Ontem fiquei curioso em saber como acessar um endereço web por através de uma conexão em um proxy autenticado então achei algumas referencias na net e fiz esse pequeno exemplo:
a seguir o código, que exibe uma caixa de dialogo para entrar com a senha:
ProxyTeste.java:
import java.io.DataInputStream;
import java.io.IOException;
import java.net.Authenticator;
import java.net.HttpURLConnection;
import java.net.PasswordAuthentication;
import java.net.URL;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.xml.ws.http.HTTPException;
public class ProxyTeste {
public static void main(String[] args) throws HTTPException, IOException {
urlDump("http://www.alandaniel.com.br");
}
public static void urlDump(String URLName){
try {
DataInputStream di = null;
byte [] b = new byte[1];
// INFORMAÇÕES DE PROXY, alterar para suas informações de proxy
System.setProperty("http.proxyHost","10.15.54.10") ;
System.setProperty("http.proxyPort", "8080") ;
// AUTENTICAÇÃO DE PROXY
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
JTextField jtf = new JTextField();
JPasswordField jpf = new JPasswordField();
if(JOptionPane.showConfirmDialog(null, new Object[]{jtf, jpf}, "Senha:", JOptionPane.OK_CANCEL_OPTION)==0){
String usuario = jtf.getText();
char[] senha = jpf.getPassword();
return new PasswordAuthentication(usuario,senha);
}else{
System.exit(0);
return null;
}
}});
//REALIZA AS CHAMADAS
URL url = new URL(URLName);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
di = new DataInputStream(con.getInputStream());
//IMPRIME CONTEUDO
while(-1 != di.read(b,0,1)) {
System.out.print(new String(b));
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Fonte: Google…







