2015-09-25 141 views
0

我正在嘗試從REST網址下載文件。下面是我用HTTP錯誤代碼:400

byte[] plainCredsBytes ="mytoken".getBytes(); 
byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes); 
String base64Creds = new String(base64CredsBytes); 
URL url = new URL("https://api.xxxxx.com/files/62645/6hSFcVs3qIbvrGdXOfYzXQ/Test.png"); 
HttpURLConnection conn = (HttpURLConnection) url.openConnection(); 
conn.setRequestMethod("GET"); 
conn.setRequestProperty("Content-type", "text/plain; charset=utf-8"); 
conn.setRequestProperty("Accept", "*/*"); 
conn.setRequestProperty("Authorization", "Basic " + base64Creds); 

我得到了java.lang.RuntimeException代碼:失敗:HTTP錯誤代碼:400

我試圖讓從反應更多的細節,這是

<?xml version="1.0" encoding="UTF-8"?> 
<Error> 
<Code>InvalidArgument</Code> 
<Message>Only one auth mechanism allowed; only the X-Amz-Algorithm query parameter, Signature query string parameter or the Authorization header should be specified</Message> 
<ArgumentName>Authorization</ArgumentName> 
<ArgumentValue>Basic M2U3YzMzODU3NmY3ZjgwNzY2OWU5Yzg5NDg0Y2Y3Mzc=  </ArgumentValue> 
<RequestId>7BDEA0EBE74A63FF</RequestId> 
<HostId>qU+xjS3nRcTbyBHPZyM89tGZC46sa9XzhkDLPD+p4oOSQc1UF9vSnpqB7A6Mlp5s76iqCOY2n+0=</HostId> 
</Error> 

我傳遞基本授權證書,如果我刪除它,我得到
HTTP錯誤代碼:401 {「消息」:「需要身份驗證」}

有什麼幫助嗎?

+0

你是如何設置base64Creds變量?你可以發佈該代碼嗎? – user2953113

+0

@ user2953113修改後的代碼包含它 – fjkjava

+0

這可以幫助http://stackoverflow.com/questions/12732422/adding-header-for-httpurlconnection –

回答

0

我得到400錯誤的請求,因爲我調用的服務驗證我的身份驗證,並將其重定向到一個不需要身份驗證的亞馬遜服務,因此它正在抱怨請求。

我不得不禁用後續的重定向,並得到了位置,然後發送另一個請求獲取文件

conn.setInstanceFollowRedirects(false); 

其實上面的程序我爲POC,我的實際客戶端使用彈簧安置模板。 ClientHttpRequestFactory的默認實現爲get執行setInstanceFollowRedirects(true),所以我必須創建一個自定義的ClientHttpRequestFactory。

public class CustomClientHttpRequestFactory extends SimpleClientHttpRequestFactory { 

@Override 
protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException { 
    ..... 
} 

}