验证错误:无法应对任何这些挑战:{} Android - 401未经授权 [英] Authentication error: Unable to respond to any of these challenges: {} Android - 401 Unauthorized

查看:132
本文介绍了验证错误:无法应对任何这些挑战:{} Android - 401未经授权的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

验证错误:无法应对任何这些挑战:{} Android - 401未经授权



我已经从此链接中引用
在Android上使用HttpPost with DefaultHttpClient 时的身份验证错误



我在Drupal支持的Android应用程序中工作。因为我正在从Android应用程序发送数据到drupal网站 - JSON格式的webservice。现在我可以从Drupal webservice读取JSON数据并将其写入我的Android应用程序。但是面对来自Android的drupal的问题,它会生成响应状态代码


401未授权


< blockquote>

从android本机应用程序生成401,而从phonegap - 从android,当我启动AJAX请求,它的工作完美&在drupal网站上写一篇文章或页面。这意味着webservice完美工作


我的phonegap android应用程序完美的工作有Android本机JAVA应用程序的问题
我在Android2.3.4上运行我的Android应用程序 - > Samsung Galaxy
S Plus - 三星GT-I9001


这是我的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();

凭证creds = new UsernamePasswordCredentials(username,password);
client.getCredentialsProvider()。setCredentials(新的AuthScope(AuthScope.ANY_HOST,AuthScope.ANY_PORT),creds);
HttpPost post = new HttpPost(url);
System.out.println(的值=============>+ 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自动生成的catch块
e3.printStackTrace();
}
try {
jsonobject = new JSONStringer()。array()。object()。key(und)。object()。key(0)。object 。).KEY( 值)的值(体).endObject()endObject()endObject()endArray()。;
System.out.println(=============>+ jsonobject);

} catch(JSONException e2){
// TODO自动生成的catch块
e2.printStackTrace();
}

列表< 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(params的值=============>+ params);

UrlEncodedFormEntity formEntity = null;
try {
formEntity = new UrlEncodedFormEntity(params);
} catch(UnsupportedEncodingException e1){
// TODO自动生成的catch块
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
{
returnHello这是status ==>:+ String.valueOf(statusCode);
}
} catch(UnsupportedEncodingException e){
// TODO自动生成的catch块
e.printStackTrace();
} catch(ClientProtocolException e){
// TODO自动生成的catch块
e.printStackTrace();
} catch(IOException e){
// TODO自动生成的catch块
e.printStackTrace();
}

返回null;
}

public static String iStream_to_String(InputStream is1){
BufferedReader rd = new BufferedReader(new InputStreamReader(is1),4096);
字符串;
StringBuilder sb = new StringBuilder();
尝试{
while((line = rd.readLine())!= null){
sb.append(line);
}
rd.close();

} catch(IOException e){
// TODO自动生成的catch块
e.printStackTrace();
}
String contentOfMyInputStream = sb.toString();
return contentOfMyInputStream;
}

}

}

这是我得到的logcat。

  08-09 12:41:29.063:I / System.out 336):帖子的值=============> 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) :params的值=============> [type = page,title = hhhh,language = und,body = [{und:{0:{value:ddddddd}}}]]
08-09 12:41: 30.913:W / DefaultRequestDirector(336):验证错误:无法应对任何这些挑战:{}
08-09 12:41:30.913:I / System.out(336):===== ====> statusCode post idea =====> 401
08-09 12:41:30.924:I / System.out(336):=========>回帖帖子=>你好这是状态==> :401

这是我的PhoneGap Ajax请求,它的工作完美。

  $('#page_node_create_submit')。live('click',function(){

var title = $('#page_node_title' ).val();
// if(!title){alert('请输入标题'); return false;}

var body = $('#page_node_body' ).val();
// if(!body){alert('Please enter a body。'); return false;}

// BEGIN:drupal services node create login (警告:如果您没有ssl设置,请不要使用https)
$ .ajax({
url:XXX,
type:'post',
data:'node [type] = page& node [title] ='+ encodeURIComponent(title)+'& node [language] = und& node [body] [und] [0] [value] ='+ encodeURIComponent身体),
dataType:'json',
error:function(XMLHttpRequest,textStatus,errorThrown){
alert('page_node_create_submit - failed to login');
控制台.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的各种方法在这段时间里,我做了一些研究,并在谷歌搜索并发现了一些有趣的东西。



第一我发现的东西Android-Google官方不建议在我的代码中使用Apache HttpClient。检查此链接。来自Dalvik团队的Jesse Wilson的Link消息。因此,他们建议使用HttpURLConnection而不是DefaultHttpClient,并写道,Android团队将不再开发Apache httpclient。所以它是我使用的旧版本。


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


第二个我发现这个链接的东西。这表明,在Android的HttpClient 4.0 Beta2中,有一个缺点,就是基本认证。我使用的Authentication方法是HttpClient 3.x,我已经发现从这个链接。
检查链接。
http://hc.apache.org/httpclient- 3.x / authentication.html#Preemptive_Authentication



所以版本问题。


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




我还发现了一些可能解决这个问题的链接。


http://ogrelab.ikratko.com/using-更新版本的httpclient-like-4-1-x /



Android上的Apache HttpClient 4.1



什么版本的Apache HTTP Client绑定在Android 1.6?


从这些链接中,我得出结论,如果我们将Apache HttpClient升级到最新的稳定版本,那么这个问题可以解决。



但是这绝对不可能,因为Android Team已经正式停止了对Apache的支持httpclient。



使用此链接可以解决。我没有尝试过,但我正在努力。



这是可以帮助升级Android中的httpclient版本的库。


http://code.google.com/ p / httpclientandroidlib /


另一个解决方案可能是使用 HttpURLConnection 。我也在工作



但是,stackoverflow和Internet上的大多数人似乎都在Android中使用 DefaultHttpCLient 。而且,在我的应用程序中,它也与我一起工作,包括登录,注册,从服务器和会话读取等功能。只是直接在我的服务器 - Drupal网站上发布一些文章。
它在服务器上的用户注册期间完美地与POST请求一起工作。



所以朋友们,有关于此的任何建议?为什么它不适用于发布文章?

解决方案

它来自于PhoneGap而不是Java。 PhoneGap在Web容器中运行该应用程序,因此已经被认证 - 并且您拥有所有正确的Cookie。不过,HTTPClient是完全不同的 - 你正在发起一个全新的HTTP会话,一切都是正确的



关于HTTP认证如何工作的几点评论:



有几种HTTP身份验证方法 - web服务器选择哪个。在进一步之前,检查您的Drupal配置是否是:





(另请注意,Web容器具有'smarts'能够尝试diffe租用身份验证方法按照服务器的要求,所有后台)



还要查看Drupal的Web日志。几个指针:




  • 您是否看到所有的HTTPClient连接 。而且是正确资源的URL。始终值得从服务器的角度检查 ...

  • 它是否转到正确的服务器?可能出错的一个例子:您是否在多宿主网络服务器上使用IP
    地址,因此请求会转到错误的服务器?

  • 检查客户端先前发送的身份验证是正确的类型(基本,摘要,NTLM)



让我知道这是否有帮助。如果没有,您可以按照这篇文章提供更多的细节,我可以跟进更多的建议。


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

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

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 Unauthorized

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 &

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

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;
            }

    }

   }

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

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;

});

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

Edit :

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.

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

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

So the version issue.

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 on Android

What version of Apache HTTP Client is bundled in Android 1.6?

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

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.

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

http://code.google.com/p/httpclientandroidlib/

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

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 ?

解决方案

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'.

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

A few comments on how HTTP Auth works:

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:

(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)

Also check the Drupal web logs. A few pointers:

  • 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.

这篇关于验证错误:无法应对任何这些挑战:{} Android - 401未经授权的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆