2016-12-12 34 views
0

發送請求時,我有以下代碼:錯誤407試圖用Java

public class SendRequest { 

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

    String url = "http://backoffice.xyz"; 

    HttpHost proxy = new HttpHost("proxy.proxy", 8080, "http"); 
    HttpClient client = HttpClientBuilder.create().setProxy(proxy).build(); 
    HttpGet request = new HttpGet(url); 

    //request.addHeader("User-Agent", "USER-AGENT"); 
    HttpResponse response = client.execute(request); 

    System.out.println("Response Code: " + response.getStatusLine().getStatusCode()); 

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

    StringBuffer result = new StringBuffer(); 
    String line = ""; 
    while((line = rd.readLine()) != null){ 
     result.append(line); 
    } 
     System.out.println(result.toString()); 

} 

}

這是返回一個407次未授權訪問/高速緩存訪​​問被拒絕錯誤。我需要包含哪些代碼才能通過代理進行身份驗證?

回答

1

您的代理是否需要基於用戶名/密碼的身份驗證?如果是這樣,請嘗試執行java.net.Authenticator。我猜你需要設置useSystemProperties

Authenticator.setDefault(new Authenticator(){ PasswordAuthentication getPasswordAuthentication(){ return new PasswordAuthentication(username, password); } });

您可能需要增加setDefaultCredentialsProvider(CredentialsProvider credentialsProvider)到HTTPClientBuilder和使用SystemDefaultCredentialsProvider實例爲。

+0

是的,那正是我需要的。你能否也請編輯我用這些行發佈的代碼?因爲,例如,我不明白在哪裏插入這個setDefault方法和credentialsProvider,這是我第一次請求代碼的代理驗證:D – Tudor

+0

我忘了提及,在這樣做的同時我也會將您的答案標記爲解決方案。 – Tudor

0

1.你可以檢查你的代理嗎?我不確定proxy.proxy是否正確。

你其餘的代碼看起來很好。

2.並且確保你正在更新httpcore版本到4.4或以上。而且你可以更新httpcore到最新版本。

3.You可以檢查你的代理服務器的身份驗證@Goutham提到

希望這有助於!

+0

Proxy.proxy就是一個例子。我需要的是基於用戶名/密碼的認證 – Tudor