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

Mob*_*ch. 12 java android json drupal httprequest

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

在Android上使用带有DefaultHttpClient的HttpPost时,我已经从此链接验证错误中引用了参考

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

401未经授权

从Android原生应用程序它生成401,而从phonegap-从Android启动AJAX请求它​​完美工作并在drupal网站上写一篇文章或页面.这意味着网络服务工作完美

我的phonegap Android应用程序工作完美有Android本机JAVA应用程序的问题我在Android2.3.4上运行我的Android应用程序 - >三星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();

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

    }

   }
Run Code Online (Sandbox Code Playgroud)

这是我得到的logcat.

 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
Run Code Online (Sandbox Code Playgroud)

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

$('#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;

});
Run Code Online (Sandbox Code Playgroud)

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

编辑:

我已经为Apache httpclient尝试了各种方法来解决我的错误.在这段时间我做了一些研究并在google上搜索并发现了一些有趣的东西.

首先我发现Android-Google正式不推荐我在我的代码中使用的Apache HttpClient.检查此链接.来自Dalvik团队的Jesse Wilson发来的链接消息.因为他们建议使用HttpURLConnection而不是DefaultHttpClient,并且还写道Android团队将不再开发Apache httpclient.所以它是我正在使用的旧版本.

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

我找到的第二件事就是这个链接.它表明 Android在Apache的HttpClient 4.0 Beta2中出货,它在基本身份验证方面存在缺陷. 我使用的身份验证方法是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-newer-version-of-httpclient-like-4-1-x/

Android上的Apache HttpClient 4.1

Android 1.6捆绑了哪个版本的Apache HTTP Client?

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

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

通过此链接可以解决.我没有尝试过,但我正在研究它.

这个库可以帮助升级Android中的httpclient版本.

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

另一个解决方案可能是使用HttpURLConnection.我也正在研究它.

但是大多数人在stackoverflow和Internet上似乎都使用DefaultHttpCLient和Android.当然,它也在我的应用程序中与我合作,包括登录,注册,从服务器和会话阅读和其他功能.只是它不能直接发布一些文章到我的服务器-Drupal网站.在服务器上注册用户期间,它与POST请求完美配合.

所以朋友们,对此有何建议?为什么它只是发布文章?

Szt*_*upY 1

您可能会尝试检查:How to do http post using apache httpclient with web authentication?

需要时,它使用 aHttpInterceptor注入身份验证数据


归档时间:

查看次数:

22879 次

最近记录:

13 年,6 月 前