验证错误:无法对任何应对这些挑战:{}机器人 - 401未授权机器人、错误

2023-09-05 10:29:45 作者:沙漏。

认证错误:无法对任何应对这些挑战:{}机器人 - 401未授权

Authentication error: Unable to respond to any of these challenges: {} Android - 401 Unauthorized

我已经参考此链接 Authentication错误时DefaultHttpClient在Android 使用HttpPost

I have taken reference from this link Authentication Error when using HttpPost with DefaultHttpClient on Android

我的工作中,在Drupal的支持Android应用程序。在此我从Android应用程序将数据发送到Drupal的网站 - webservice的JSON格式。现在,我可以读Drupal的Web服务的JSON数据,并写在我的Andr​​oid应用程序。但在写作上的机器人的Drupal面临的问题,它产生的反应与状态code

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

401未授权

这是Android原生应用程序,它会产生401,而从PhoneGap的 - 从机器人,当我发起AJAX请求它​​完美的作品和放大器;写在Drupal的网站上的文章或网页。这样就意味着Web服务的工作完全与放大器;

From android native app it generates 401 , while from phonegap-from android when I initiate AJAX request it works perfectly & writes an article or page on drupal website. so that means webservice work perfectly &

我的PhoneGap的Andr​​oid应用程序完美的作品存在的问题与Android原生JAVA应用   我上运行的Andr​​oid2.3.4我的Andr​​oid应用程序 - >三星Galaxy   小号加 - 三星GT-I9001

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

这是我的code对Java的Andr​​oid。

here is my code for java android.

==============================

==============================

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 =============> "+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=======>"+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("=============>"+jsonobject);

        } catch (JSONException e2) {
            // TODO Auto-generated catch block
            e2.printStackTrace();
        }

         List<NameValuePair> params = new ArrayList<NameValuePair>();

                 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 =============> "+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("=========> statusCode post idea=====> "+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 ==> :"+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;
            }

    }

   }

下面是我收到的logcat。

here is the logcat that I am getting.

 08-09 12:41:29.063: I/System.out(336): value of the post =============>      org.apache.http.client.methods.HttpPost@4053c3c8
 08-09 12:41:29.093: I/System.out(336): @@@@@@2    jsonnode=======>{"und":  [{"value":"ddddddd"}]}
 08-09 12:41:29.093: I/System.out(336): =============>[{"und":{"0":{"value":"ddddddd"}}}]
 08-09 12:41:29.103: I/System.out(336): value of the params =============> [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): =========> statusCode post idea=====> 401
 08-09 12:41:30.924: I/System.out(336): =========> Response from post  idea => Hello This is status ==> :401

下面是我的PhoneGap Ajax请求它完美的作品。

Here is my PhoneGap Ajax request it works perfectly.

$('#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&node[title]=' + encodeURIComponent(title) +  '&node[language]=und&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;

});

=============================================== ==================================

=================================================================================

我已经试过各种方法为Apache的HttpClient我error.During这次我做了一些调查和搜索谷歌和发现了一些有趣的东西。

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.

第1 的事情,我发现它是Android的谷歌官方不推荐的Apache HttpClient的,我用我的code。检查此链接。在从杰西·威尔逊该链接的消息从Dalvik的团队。在他们建议使用HttpURLConnection的,而不是DefaultHttpClient也撰文指出,Android团队将不再开发的Apache的HttpClient。所以它的旧版本,我使用。

1st 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.

http://android-developers.blogspot.in/2011/09/androids-http-clients.html

2日的事情,我发现这种形式的链接。这表明,机器人是航运与Apache的HttpClient的4.0 Beta2中,其中有一个缺陷,当它涉及到基本身份验证。我使用的身份验证方法的HttpClient 3.x中,我发现了从这个链接。 检查线路。  http://hc.apache.org/httpclient-3.x/authentication.html#$p$pemptive_Authentication

2nd thing that I have found form this link. It suggests that Android is shipping with Apache's HttpClient 4.0 Beta2, which has a pitfall, when it comes to Basic Authentication. The Authentication method that I am using is of HttpClient 3.x , that I have found out from this link. check the link. http://hc.apache.org/httpclient-3.x/authentication.html#Preemptive_Authentication

于是版本问题。

http://dlinsin.blogspot.in/2009/08/http-basic-authentication-with-android.html

我还发现这个问题的潜在解决方案的一些链接。

I have also found some links with potential solution of this problem.

http://ogrelab.ikratko.com/using-newer-version-of-httpclient-like-4-1-x/

的Apache的HttpClient 4.1在Android

What版本的Apache HTTP客户端捆绑在Android 1.6的?

从这些链接,我做了一个结论,即如果我们升级了Apache的HttpClient到最新的稳定版本,那么这个问题是可以解决的。

From these links , I made a conclusion that if we upgrade the Apache HttpClient to latest stable version , then this problem can be solved.

但是,这是直接没有可能的,因为Android团队已经正式停止了Apache的HttpClient。

But this is directly no possible , as Android Team has officially stopped the support for the Apache httpclient.

通过这个链接它可能是可以解决的。我还没有尝试过,但我的工作就可以了。

With this link It could be possible to solve. I have not tried it but I am working on it.

这是库,可以在Android的升级版本的HttpClient帮助。

It is the library that can help in upgrading httpclient version in Android.

http://$c$c.google.com/p/httpclientandroidlib/

另一种解决方案可能是使用的的HttpURLConnection 。我自己也是在努力。

The other solution could be using HttpURLConnection .I am also working on it.

不过,这里计算器和互联网大多数人似乎用 DefaultHttpCLient 与Android。而且ofcourse它也正在与我在我的应用程序,包括登录,注册,从服务器和会话等functionality.Just读它不与工作直接发布一些文章到我的服务器的Drupal网站。 它可以完美地与用户在服务器上注册时POST请求。

But most people here on stackoverflow and Internet seems to using DefaultHttpCLient 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.

因此​​,朋友们,对此有什么建议?为什么它不工作只用张贴文章?

So friends , any suggestions regarding this ? why it is not working just with posting article ?

推荐答案

它是如何来工作的PhoneGap的,但不是Java。 PhoneGap的运行在Web容器中的应用程序,因此已经被验证 - 你拥有所有正确的cookies。 AJAX将共享同一个会话,一切只是工作。

How come it works from the PhoneGap but not Java. PhoneGap runs the app in a web container and so already has been authenticated - and you have all the right cookies. AJAX will share the same session that and everything 'just works'.

不过了HTTPClient是一个完全不同的 - 你正在发起一个全新的HTTP会话,一切都必须正确

However HTTPClient is a completely different - you are initiating a brand new HTTP session and everything has to be right.

在HTTP认证是如何工作的几点意见:

A few comments on how HTTP Auth works:

有几个HTTP验证方法 - 这是该选择的Web服务器。在继续之前,请检查您的Drupal的配置,以找出是否是:

There are several HTTP authentication methods - and it's the web server that chooses which. Before going any further, check your Drupal configuration to work out whether it is:

在基本认证(用户名和密码)。每个人都和他们的狗支持这一点,但它是非常不安全的。请参见 http://en.wikipedia.org/wiki/Basic_access_authentication 了解更多详细信息 。在摘要(用户名和质询/响应哈希值MD5这是比较安全的,但要复杂得多注意,MD5目前通常认为是弱许多图书馆支持,包括Apache见的 http://en.wikipedia.org/wiki/Digest_access_authentication 查看详细信息 在NTLM(的Kerberos / SPEGNO的变体),这是在IIS上实现的。这不是一般从Java的支持,虽然它的HTTPClient自称 - 但使用不同的凭据对象。请参见 http://hc.apache.org/httpclient-3.x/ authentication.html#NTLM Basic Auth (username and password). Everyone and their dog supports this, but it's very insecure. See http://en.wikipedia.org/wiki/Basic_access_authentication for more details Digest (username and challenge/response hash with MD5. This is more secure but much more complex. Note that MD5 is generally considered weak now. Many libraries support it, including Apache. See http://en.wikipedia.org/wiki/Digest_access_authentication for more details NTLM (a variant of Kerberos/SPEGNO) which is implemented on IIS. This is not generally supported from Java, although HTTPClient does profess to - but using a different Credentials object. See http://hc.apache.org/httpclient-3.x/authentication.html#NTLM

(另请注意,Web容器有智慧,能够尝试不同的身份验证方法所要求的服务器上,所有在幕后)

(Note also that the web container has the 'smarts' to be able to try different authentication methods as requested by the server, all behind the scenes)

另外,还要检查Drupal的网络日志。几个指针:

Also check the Drupal web logs. A few pointers:

你看到HttpClient的连接的所有的。而且是要正确的资源的URL。始终值得一试的从服务器的角度看 ... 在它是否到正确的服务器?什么可能出问题的一个例子:你使用的IP 在对多宿主的Web服务器的URL地址,所以请求进入到错误的服务器? 检查客户端pre-先发制人是正确的类型(基本,摘要,NTLM)发送的认证 Did you see the HTTPClient connect at all. And is the URL going to the correct resource. Always worth checking from the server's perspective... Did it go to the right server? One example of what could go wrong: Are you using IP addresses in the URL against a multi-homed web server, so the request goes to the wrong server? Check that the authentication sent by the client pre-emptively is the correct type (basic, digest, NTLM)

让我知道,如果这有助于。如果没有,你可以提供更多的细节按这个职位,我可以跟更多的建议。

Let me know if this helps. If not, and you can give more details as per this post, I can follow up with more advice.