Android HTTP Authentication error
-
09-06-2021 - |
Question
final HttpClient hClient = new DefaultHttpClient();
final HttpPost hPost = new HttpPost(
"http://xxx.xxx");
try {
hPost.setHeader("Accept", "application/json");
hPost.setHeader("Content-type",
"application/json");
hPost.setEntity(new StringEntity(JSON));
// execute request
final HttpResponse response = hClient
.execute(hPost);
final HttpEntity entity = response.getEntity();
Android returns 05-16 20:02:52.784: W/DefaultRequestDirector(15642): Authentication error: Unable to respond to any of these challenges: {} and I don't know how to fix it. Where is the problem and how can I fix it?
Solution
Try setting the Http parameters as following:
HttpParams myParams = new BasicHttpParams();
HttpConnectionParams.setSoTimeout(myParams, 10000);
HttpConnectionParams.setConnectionTimeout(myParams, 10000); // Timeout
DefaultHttpClient httpClient = new DefaultHttpClient(myParams);
For the http post and response you can try the following code. Kindly customize according to your needs (for example set your string parameters)
HttpResponse response;
httpClient.getParams().setParameter("Your String", "YourStringValue");
localContext = new BasicHttpContext();
HttpPost httpPost = new HttpPost(YOurURL);
Log.e("URL", URL); //just to check
httpClient.getParams().setParameter(ClientPNames.COOKIE_POLICY,CookiePolicy.RFC_2109);
StringEntity tmp = null;
httpPost.setHeader("Accept", "application/json");
tmp = new StringEntity(inputJObject.toString(), "UTF-8");
httpPost.setEntity(tmp);
response = httpClient.execute(httpPost, localContext);
Log.i(TAG, response.getStatusLine().toString()); // Examine the response status
HttpEntity entity = response.getEntity(); // Get hold of the response entity
OTHER TIPS
I had this warning as well, but it did not caused any particular problems, the request still goes fine.
However I stopped getting this error as soon as I started using AndroidHttpClient
instead of the DefaultHttpClient
. One uncomfortable thing is that you cannot use AndroidHttpClient
from UI thread and need to run it on another thread.
I got this error and resolved it by going back to basics! The error was generated from a request to https://www.googleapis.com/oauth2/v1/userinfo. The solution is posted below:
URLConnection conn = (HttpURLConnection) url.openConnection();
conn.addRequestProperty("key", API_KEY);
conn.addRequestProperty("client_id", CLIENT_ID);
conn.addRequestProperty("client_secret", "");
conn.setRequestProperty("Authorization", "OAuth " + token);
All the add requests are HTTPGET key/values and the setProperty adds an header parameter. As Google API Console does not give a client secret in its current version, I added a balnk string..this solves the AuthToken to user data affair finally :)