UnknownHostException in Java

2019-07-16 03:13发布

I am using below code to connect to a url. Iam getting this error while executing it in my office system. but on my personal laptop it is working. I think it has to do something with the proxy. i have the proxy details . but how to specify it in the below code??

java.net.UnknownHostException: www.google.com

import java.util.Properties;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.methods.GetMethod;

public class test {

public static void main(String args[]) throws Exception {
  HttpClient client = new HttpClient();                   
   GetMethod method = new GetMethod("http://www.google.com");
 try{
      client.executeMethod(method);
  }catch(Exception e) { 
      System.err.println(e); 
  }finally { 
      method.releaseConnection(); 
  }
 }
}

标签: java proxy
1条回答
smile是对你的礼貌
2楼-- · 2019-07-16 03:40

From KodeJava

HttpClient client = new HttpClient();
HttpMethod method = new GetMethod("http://www.kodejava.org");
HostConfiguration config = client.getHostConfiguration();

config.setProxy(PROXY_HOST, PROXY_PORT);
String username = "guest"; String password = "s3cr3t";
Credentials credentials = new UsernamePasswordCredentials(username, password);
AuthScope authScope = new AuthScope(PROXY_HOST, PROXY_PORT);
client.getState().setProxyCredentials(authScope, credentials);

And then use your existing code to execute the method.

查看更多
登录 后发表回答