2015-02-11 97 views
0

我想編寫一個程序來使用提供程序的REST服務。通過代理配置拒絕連接

我的問題是,有一個代理用戶/密碼認證,我無法解決這個問題。

它不使用代理,但我需要使用代理。

這是我的代碼沒有代理配置。

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStreamReader; 

import org.apache.http.HttpResponse; 
import org.apache.http.client.ClientProtocolException; 
import org.apache.http.client.HttpClient; 
import org.apache.http.client.methods.HttpGet; 
import org.apache.http.impl.client.DefaultHttpClient; 

@SuppressWarnings("deprecation") 

public class callAPI { 

public callAPI() { 
    // TODO Auto-generated constructor stub 
} 

public static void main(String[] args) throws ClientProtocolException, 
     IOException { 

    //System.setProperty("java.net.useSystemProxies", "true"); 
    @SuppressWarnings("resource") 
    HttpClient client = new DefaultHttpClient(); 

    HttpGet request = new HttpGet(
      "URL"); 

    HttpResponse response = client.execute(request); 

    BufferedReader rd = new BufferedReader(new InputStreamReader(response 
      .getEntity().getContent())); 

    String line = ""; 

    while ((line = rd.readLine()) != null) { 

     System.out.println(line); 

    } 

} 

} 

從來就閱讀所有文章,並試圖做到這一點在我的代碼,但總是得到同樣的錯誤(拒絕連接)。

提前致謝!

回答

0

從例如Apache doco

HttpHost target = new HttpHost("localhost", 443, "https"); 
HttpHost proxy = new HttpHost("127.0.0.1", 8080, "http"); 

RequestConfig config = RequestConfig.custom() 
      .setProxy(proxy) 
      .build(); 
HttpGet request = new HttpGet("/"); 
request.setConfig(config); 

CloseableHttpResponse response = httpclient.execute(target, request); 

兩者你也可以嘗試添加

Authenticator.setDefault(new Authenticator() { 
    protected PasswordAuthentication getPasswordAuthentication() { 
     return new PasswordAuthentication(username, password.toCharArray()); 
    } 
}); 
+0

我得到 「的java.net.UnknownHostException」,但uri是正確。如果我通過網絡瀏覽器嘗試,我可以訪問該服務。在那個例子中用戶/密碼沒有定義。 – Javi 2015-02-11 11:26:04

0

嘗試使用

System.getProperties().put("http.proxyHost", "ProxyURL"); 
System.getProperties().put("http.proxyPort", "ProxyPort"); 
System.getProperties().put("http.proxyUser", "UserName"); 
System.getProperties().put("http.proxyPassword", "Password"); 
+0

我試過了,我也得到了同樣的錯誤。 – Javi 2015-02-11 11:25:10