身份验证错误:无法响应以下任何质询:{} Android - 401 Unauthorized
我已从此链接参考在 Android 上使用 HttpPost 和 DefaultHttpClient 时出现身份验证错误 https://stackoverflow.com/questions/6114455/authentication-error-when-using-httppost-with-defaulthttpclient-on-android
我正在开发由 Drupal 支持的 Android 应用程序。我正在将数据从 android 应用程序发送到 drupal 网站 - JSON 格式的 web 服务。现在我可以从 Drupal Web 服务读取 JSON 数据并将其写入我的 Android 应用程序中。但是在 android 上编写 drupal 时遇到问题,它会生成带有状态代码的响应
401 未经授权
从android本机应用程序它生成 401 ,而从phonegap-from android当我启动AJAX请求时它完美地工作并在drupal网站上写一篇文章或页面。这意味着网络服务可以完美工作&
我的phonegap android应用程序运行完美,但Android本机JAVA应用程序有问题
我正在 Android2.3.4 -> Samsung Galaxy 上运行我的 Android 应用程序
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;
}
}
}
这是我得到的 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
这是我的 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;
});
=================================================== ===============================
Edit :
我为 Apache httpclient 尝试了各种方法来解决我的错误。在这段时间里,我做了一些研究并在 google 上搜索,发现了一些有趣的东西。
1st我发现 Android-Google 官方不推荐我在代码中使用 Apache HttpClient。检查此链接。在来自 Dalvik 团队的 Jesse Wilson 的链接消息中。他们建议使用 HttpURLConnection 而不是 DefaultHttpClient ,并且还写道 Android 团队将不再开发 Apache httpclient 。所以我使用的是旧版本。
http://android-developers.blogspot.in/2011/09/androids-http-clients.html http://android-developers.blogspot.in/2011/09/androids-http-clients.html
2nd我从这个链接中找到的东西。它表明Android 附带了 Apache 的 HttpClient 4.0 Beta2,它在基本身份验证方面存在缺陷。我使用的身份验证方法是 HttpClient 3.x ,我是从此链接中找到的。
检查链接。http://hc.apache.org/httpclient-3.x/authentication.html#Preemptive_Authentication http://hc.apache.org/httpclient-3.x/authentication.html#Preemptive_Authentication
所以版本问题。
http://dlinsin.blogspot.in/2009/08/http-basic-authentication-with-android.html 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/ http://ogrelab.ikratko.com/using-newer-version-of-httpclient-like-4-1-x/
Android 上的 Apache HttpClient 4.1 https://stackoverflow.com/questions/3577035/apache-httpclient-4-1-on-android
Android 1.6 中捆绑了哪个版本的 Apache HTTP 客户端? https://stackoverflow.com/questions/2618573/what-version-of-apache-http-client-is-bundled-in-android-1-6
从这些链接中,我得出的结论是,如果我们将 Apache HttpClient 升级到最新的稳定版本,那么这个问题就可以解决。
但这是不可能的,因为 Android 团队已经正式停止了对 Apache httpclient 的支持。
有了这个链接就可以解决。我还没有尝试过,但我正在努力。
这是一个可以帮助升级Android中的httpclient版本的库。
http://code.google.com/p/httpclientandroidlib/ http://code.google.com/p/httpclientandroidlib/
另一种解决方案可以使用HttpURL连接.我也在努力。
但 stackoverflow 和互联网上的大多数人似乎都在使用默认Http客户端与安卓。当然,它也在我的整个应用程序中与我一起工作,包括登录、注册、从服务器和会话读取以及其他功能。只是它不能直接将一些文章发布到我的服务器 Drupal 网站。
在服务器上注册用户期间,它与 POST 请求完美配合。
那么朋友们,对此有什么建议吗?为什么它不能仅用于发布文章?