Reputation: 3345
I have tried multiple things to correct this and not sure what the issue is. For the POST request I have tried encoding the username credentials in Base64 and and set as requestProperty values. Also tried adding it as parameters to the POST body but in both instances the request fails with a 401 error. Clearly the credentials are not being recognized although when used in POSTMAN request it works fine. I then duplicated the headers used in that request with the BASIC auth value and still the same error code. Perhaps I am not seeing the issue clearly:
obj = new URL(urlRequest);
conn = (HttpsURLConnection) obj.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("User-Agent", "PostmanRuntime/7.28.3");
conn.setRequestProperty("Accept", "*/*");
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("Content-Type","multipart/form-data");
//String userCredentials = "_username=xxxxxxxx&_password=yyyyyyyy";
//String basicAuth = "Basic " + new
String(Base64.getEncoder().encode(userCredentials.getBytes()));
//conn.setRequestProperty("Authorization", basicAuth);
conn.setRequestProperty("_username", "xxxxxxxxxx");
conn.setRequestProperty("_password", "yyyyyyyyyy");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("_username", "xxxxxxxxxx"));
params.add(new BasicNameValuePair("_password", "yyyyyyyyyy"));
String urlParameters = "_username=xxxxxxxxxx&_password=yyyyyyyyyy";
conn.setDoOutput(true);
try (DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
wr.writeBytes(urlParameters);
wr.flush();
}
InputStream urlInputStream;
int errCode = conn.getResponseCode();
BufferedReader inSt = new BufferedReader(new InputStreamReader(conn.getInputStream(),
"UTF-8"));
StringBuilder response = new StringBuilder();
Upvotes: 0
Views: 934
Reputation: 2687
In the HTTP Basic authentication scheme Base64 encoded credentials are in form of username:password
. Try this:
String username = "xxxxxxxxxx", password = "yyyyyyyyyy";
conn.setRequestProperty("Authorization", "Basic " +
Base64.getEncoder().encodeToString(
(username + ":" + password).getBytes()));
RFC2617: HTTP Authentication: Basic and Digest Access Authentication
To receive authorization, the client sends the userid and password, separated by a single colon (":") character, within a base64 encoded string in the credentials.
(As a side note: You can't have colon in the username.)
If content is not in multipart format the Content-Type
header should be changed accordingly. In case of content format key1=value1&key2=value2&...
try this:
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
See this answer for more information.
Upvotes: 1