title: Authentication error: Unable to respond to any of these challenges: {} Android - 401 Unauthorized
body: <p>Authentication error: Unable to respond to any of these challenges: {}    Android - 401 Unauthorized</p>
  
  <p>I have taken reference from this link 
  <a href="https://stackoverflow.com/questions/6114455/authentication-error-when-using-httppost-with-defaulthttpclient-on-android">Authentication Error when using HttpPost with DefaultHttpClient on Android</a></p>
  
  <p>I am working on android app in that backed in Drupal. In that I am sending data from android app to drupal website - webservice in JSON format. Now I can read JSON data from Drupal webservice and writing it in my android application. But facing problem in writing on drupal from android, it generates response with status code </p>
  
  <blockquote>
    <p>401 Unauthorized</p>
  </blockquote>
  
  <p>From android native app it generates 401 , while from phonegap-from android when I initiate AJAX request it works perfectly &amp; writes an article or page on drupal website. so that means webservice work perfectly &amp; </p>
  
  <blockquote>
    <p>my phonegap android app works perfectly there is problem with Android native JAVA application
    I am running my android application on Android2.3.4 -> Samsung Galaxy
    S Plus - Samsung GT-I9001</p>
  </blockquote>
  
  <p>here is my code for java android.</p>
  
  <p>==============================</p>
  
  <pre><code>String url = "XXX";
  strResponse1 = makeWebForPostIdea(url,title,body);
  
  public static String makeWebForPostIdea(String url, String title,String body)
      {
          JSONStringer jsonobject = null;
          JSONObject json = null;
          JSONObject jsonnode = null;
  
          DefaultHttpClient client = new DefaultHttpClient();
  
  Credentials creds = new UsernamePasswordCredentials("username", "password");
          client.getCredentialsProvider().setCredentials(new       AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT), creds);
   HttpPost post = new HttpPost(url);
  System.out.println("value of the post =============&gt; "+post);
   try {
              JSONObject jsonvalue = new JSONObject();
              jsonvalue.put("value", body.toString());
  
              JSONArray array = new JSONArray();
              array.put(jsonvalue);
  
              jsonnode = new JSONObject();
              jsonnode.put("und", array);
  
              System.out.println("@@@@@@2    jsonnode=======&gt;"+jsonnode.toString());
  
  
          } catch (JSONException e3) {
              // TODO Auto-generated catch block
              e3.printStackTrace();
          }
   try {
   jsonobject = new JSONStringer().array().object().key("und").object().key("0").object().key("value").value(body).endObject().endObject().endObject().endArray();
      System.out.println("=============&gt;"+jsonobject);
  
          } catch (JSONException e2) {
              // TODO Auto-generated catch block
              e2.printStackTrace();
          }
  
           List&lt;NameValuePair&gt; params = new ArrayList&lt;NameValuePair&gt;();
  
                   params.add(new BasicNameValuePair("type","page"));
  
              params.add(new BasicNameValuePair("title",title));
              params.add(new BasicNameValuePair("language","und"));
              params.add(new BasicNameValuePair("body",jsonobject.toString()));
  
              System.out.println("value of the params =============&gt; "+params);
  
          UrlEncodedFormEntity formEntity = null;
          try {
                  formEntity = new UrlEncodedFormEntity(params);
          } catch (UnsupportedEncodingException e1) {
              // TODO Auto-generated catch block
              e1.printStackTrace();
          }
  
          post.setEntity(formEntity);
  
          try {
  
              HttpResponse response = client.execute(post);
  
              int statusCode = response.getStatusLine().getStatusCode();
              System.out.println("=========&gt; statusCode post idea=====&gt; "+statusCode);    
              if (statusCode == HttpStatus.SC_OK)
              {
                  HttpEntity entity = response.getEntity();
                  InputStream is = entity.getContent();
                  return iStream_to_String(is);
              }
              else
              {
                  return "Hello This is status ==&gt; :"+String.valueOf(statusCode);
              }
          } catch (UnsupportedEncodingException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          } catch (ClientProtocolException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          } catch (IOException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
          }
  
          return null;
      }
  
       public static String iStream_to_String(InputStream is1) {
              BufferedReader rd = new BufferedReader(new InputStreamReader(is1), 4096);
              String line;
              StringBuilder sb = new StringBuilder();
              try {
                  while ((line = rd.readLine()) != null) {
                      sb.append(line);
                  }
                  rd.close();
  
              } catch (IOException e) {
                  // TODO Auto-generated catch block
              e.printStackTrace();
          }
          String contentOfMyInputStream = sb.toString();
          return contentOfMyInputStream;
              }
  
      }
  
     }
  </code></pre>
  
  <p>here is the logcat that I am getting.</p>
  
  <pre><code> 08-09 12:41:29.063: I/System.out(336): value of the post =============&gt;      org.apache.http.client.methods.HttpPost@4053c3c8
   08-09 12:41:29.093: I/System.out(336): @@@@@@2    jsonnode=======&gt;{"und":  [{"value":"ddddddd"}]}
   08-09 12:41:29.093: I/System.out(336): =============&gt;[{"und":{"0":{"value":"ddddddd"}}}]
   08-09 12:41:29.103: I/System.out(336): value of the params =============&gt; [type=page, title=hhhh, language=und, body=[{"und":{"0":{"value":"ddddddd"}}}]]
   08-09 12:41:30.913: W/DefaultRequestDirector(336): Authentication error: Unable to respond to any of these challenges: {}
   08-09 12:41:30.913: I/System.out(336): =========&gt; statusCode post idea=====&gt; 401
   08-09 12:41:30.924: I/System.out(336): =========&gt; Response from post  idea =&gt; Hello This is status ==&gt; :401
  </code></pre>
  
  <p>Here is my PhoneGap Ajax request it works perfectly.</p>
  
  <pre><code>$('#page_node_create_submit').live('click',function(){
  
    var title = $('#page_node_title').val();
    //if (!title) { alert('Please enter a title.'); return false; }
  
    var body = $('#page_node_body').val();
    //if (!body) { alert('Please enter a body.'); return false; }
  
    // BEGIN: drupal services node create login (warning: don't use https if you don't     have ssl setup)
    $.ajax({
        url: "XXX",
        type: 'post',
        data: 'node[type]=page&amp;node[title]=' + encodeURIComponent(title) +  '&amp;node[language]=und&amp;node[body][und][0][value]=' + encodeURIComponent(body),
        dataType: 'json',
        error: function(XMLHttpRequest, textStatus, errorThrown) {
          alert('page_node_create_submit - failed to login');
          console.log(JSON.stringify(XMLHttpRequest));
          console.log(JSON.stringify(textStatus));
          console.log(JSON.stringify(errorThrown));
        },
        success: function (data) {
        $.mobile.changePage("index.html", "slideup");
       }
    });
    // END: drupal services node create
  
    return false;
  
  });
  </code></pre>
  
  <p>=================================================================================</p>
  
  <h1>Edit :</h1>
  
  <p>I have tried various methods for Apache httpclient for my error.During this time I have done some research and searched on google and found out some interesting stuff.</p>
  
  <p><strong>1st</strong> thing that I found it that Android-Google Officially does not recommend Apache HttpClient that I am using in my code. Check this link. In that Link message from  Jesse Wilson from the Dalvik team. In that they suggest to use HttpURLConnection instead of DefaultHttpClient and also written that Android team will no longer develop Apache httpclient . so its the older version that I am using.</p>
  
  <blockquote>
    <p><a href="http://android-developers.blogspot.in/2011/09/androids-http-clients.html" rel="nofollow noreferrer">http://android-developers.blogspot.in/2011/09/androids-http-clients.html</a></p>
  </blockquote>
  
  <p><strong>2nd</strong> thing that I have found form this link. It suggests that  <strong>Android is shipping with Apache's HttpClient 4.0 Beta2, which has a pitfall, when it comes to Basic Authentication.</strong>   The Authentication method that I am using is of HttpClient 3.x , that I have found out from this link. 
  check the link.
   <a href="http://hc.apache.org/httpclient-3.x/authentication.html#Preemptive_Authentication" rel="nofollow noreferrer">http://hc.apache.org/httpclient-3.x/authentication.html#Preemptive_Authentication</a></p>
  
  <p>So the version issue.  </p>
  
  <blockquote>
    <p><a href="http://dlinsin.blogspot.in/2009/08/http-basic-authentication-with-android.html" rel="nofollow noreferrer">http://dlinsin.blogspot.in/2009/08/http-basic-authentication-with-android.html</a></p>
  </blockquote>
  
  <p>I have also found some links with potential solution of this problem.</p>
  
  <blockquote>
    <p><a href="http://ogrelab.ikratko.com/using-newer-version-of-httpclient-like-4-1-x/" rel="nofollow noreferrer">http://ogrelab.ikratko.com/using-newer-version-of-httpclient-like-4-1-x/</a></p>
    
    <p><a href="https://stackoverflow.com/questions/3577035/apache-httpclient-4-1-on-android">Apache HttpClient 4.1 on Android</a></p>
    
    <p><a href="https://stackoverflow.com/questions/2618573/what-version-of-apache-http-client-is-bundled-in-android-1-6">What version of Apache HTTP Client is bundled in Android 1.6?</a></p>
  </blockquote>
  
  <p>From these links , I made a conclusion that if we upgrade the Apache HttpClient to latest stable version , then this problem can be solved.</p>
  
  <p>But this is directly no possible , as Android Team has officially stopped the support for the Apache httpclient.</p>
  
  <p>With this link It could be possible to solve. I have not tried it but I am working on it.</p>
  
  <p>It is the library that can help in upgrading httpclient version in Android.</p>
  
  <blockquote>
    <p><a href="http://code.google.com/p/httpclientandroidlib/" rel="nofollow noreferrer">http://code.google.com/p/httpclientandroidlib/</a></p>
  </blockquote>
  
  <p>The other solution could be using <strong>HttpURLConnection</strong> .I am also working on it.</p>
  
  <p>But most people here on stackoverflow and Internet seems to using <strong>DefaultHttpCLient</strong> with Android. And ofcourse it is also working with me throughout my application including login,registration,reading from server and session and other functionality.Just it is not working with directly post some article to my server-Drupal website.
  It works perfectly with POST request during registration of user on server.</p>
  
  <p>So friends , any suggestions regarding this ? why it is not working just with posting article ?</p>