I am newbie to android and this is my first project on android. I am struggling with "authentication" problem for more than a day. I tried several options but none of them worked.
Basically, I want to call a REST API and get response. I am sure that there is no problem in API as I use the same one in another iOS application.
I pass authorization header but still authentication no found message is shown. I found few question on stackoverflow related to this, but some of them did not work and some does not make sense to me.
I get status code 401
. I know this means either no authentication passed or if passed, then they are wrong. Here, I am sure my passed ones are correct.
Below is my code :
try {
url = new URL(baseUrl);
}
catch (MalformedURLException me) {
Log.e(TAG, "URL could not be parsed. URL : " + baseUrl + ". Line : " + getLineNumber(), me);
me.printStackTrace();
}
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod(method);
urlConnection.setConnectTimeout(TIMEOUT * 1000);
urlConnection.setChunkedStreamingMode(0);
// Set HTTP headers
String authString = "username:password";
String base64Auth = Base64.encodeToString(authString.getBytes(), Base64.DEFAULT);
urlConnection.setRequestProperty("Authorization", "Basic " + base64Auth);
urlConnection.setRequestProperty("Accept", "application/json");
urlConnection.setRequestProperty("Content-type", "application/json");
if (method.equals("POST") || method.equals("PUT")) {
// Set to true when posting data
urlConnection.setDoOutput(true);
// Write data to post to connection output stream
OutputStream out = urlConnection.getOutputStream();
out.write(postParameters.getBytes("UTF-8"));
}
try {
// Get response
in = new BufferedInputStream(urlConnection.getInputStream());
}
catch (IOException e) {
Log.e(TAG, "Exception in getting connection input stream. in : " + in);
e.printStackTrace();
}
// Read the input stream that has response
statusCode = urlConnection.getResponseCode();
Log.d(TAG, "Status code : " + statusCode);
}
catch (ProtocolException pe) {
pe.printStackTrace();
}
catch (IllegalStateException ie) {
ie.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
finally {
urlConnection.disconnect();
}
Look at screenshot of logcat :
Any help would be appreciated. Thank you.
No comments:
Post a Comment