0

I am trying to download a file from REST url. Here is the code that I use

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);

I am getting java.lang.RuntimeException: Failed : HTTP error code : 400

I tried to get more details from the response and here it is

<?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>

I am passing basic authorization credentials, if I remove it I get
HTTP error code : 401 {"message":"Requires authentication"}

Any help?

fjkjava
  • 1,414
  • 1
  • 19
  • 24

1 Answers1

0

I was getting 400 Bad request because the service I invoked verifies my authentication and redirects it to an amazon service which does not require authentication so it was complaining about the request.

I had to disable the follow redirect and get the location then send another request to get the file

conn.setInstanceFollowRedirects(false);

Actually the above program I did for poc, my actual client is using spring rest template. Default implementation for ClientHttpRequestFactory does setInstanceFollowRedirects(true) for GET so I had to create a custom ClientHttpRequestFactory.

public class CustomClientHttpRequestFactory extends SimpleClientHttpRequestFactory {

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

}

fjkjava
  • 1,414
  • 1
  • 19
  • 24