Labels

Showing posts with label proxyUtils. Show all posts
Showing posts with label proxyUtils. Show all posts

Thursday, March 1, 2012

ProxyUtils

Hoje eu precisei acessar uma link usando Java, até ai tudo bem, é só usar a classe URLConnection e pronto. Mas existia um proxy no caminho, e foi ai que tive que pesquisar como setar o proxy na aplicação para que ela pudesse acessar os links na Web. Depois de ler muitos fóruns, blogs, etc. Desenvolvi um método para usar em futuros projetos.

Código:
package com.blogspot.rozolin.utils;

import java.net.Authenticator;
import java.net.PasswordAuthentication;

public class ProxyUtils {
 // Não é necessario instanciar essa classe
 private ProxyUtils() {
 }
 
 public static void setProxy(String host, String porta,final String usuario, final String senha){
  setProxy(host, porta);
  
  Authenticator.setDefault(new Authenticator() {
   protected PasswordAuthentication getPasswordAuthentication() {
    return new PasswordAuthentication(usuario, senha
      .toCharArray());

   }
  });
 }
 
 public static void setProxy(String host, String porta){
  System.getProperties().put("http.proxySet", "true");
  System.getProperties().put("http.proxyHost", host);
  System.getProperties().put("http.proxyPort", porta); 
 }  
}