Android-具有基本身份验证的HttpClient JSON POST [英] Android - HttpClient JSON POST with Basic Authentication
问题描述
我正在尝试在URL上实现一个简单的JSON
帖子,该帖子通过ANDROID
上的基本身份验证接受正文中的JSON
.
I am trying to implement a simple JSON
post to the URL that accepts JSON
in body with basic authentication on ANDROID
.
我尝试使用HttpUrlConnection
,但是得到"unauthorized"
,并且我的数据被发送到服务器.
I have tried with HttpUrlConnection
but I get "unauthorized"
and my data gets send to the server.
我尝试过的另一种方法是使用HttpClient
,但是现在我遇到了另一个问题.身份验证可以完美运行,但是数据不会发送到服务器...
Another way I tried is using HttpClient
, but now I get a different problem. Authentication works perfect but the data is not sent to the server...
可以肯定的是,我在一个简单的Java项目(不是Android环境)中设置了一个小测试.
Just to be sure, I setup a small test in a simple Java project (not Android Environment).
这是我用来POST
到服务器的代码:
This is the code that I am using to POST
to the server:
DefaultHttpClient httpClient = new DefaultHttpClient();
ResponseHandler<String> resonseHandler = new BasicResponseHandler();
HttpPost postMethod = new HttpPost("http://localhost/api/v1/purchase/");
postMethod.setEntity(new StringEntity("{\"amount_adult\" : 1, \"object_id\" : 13}"));
postMethod.setHeader( "Content-Type", "application/json");
String authorizationString = "Basic " + Base64.encodeToString(("travelbuddy" + ":" + "travelbuddy").getBytes(), Base64.DEFAULT); //this line is diffe
postMethod.setHeader("Authorization", authorizationString);
String response = httpClient.execute(postMethod,resonseHandler);
System.out.println("response :" + response);
Java项目中的代码可以完美运行.
The code in the Java project works perfect.
当我在Android中尝试完全相同的代码时,我从服务器获取了internal server error
,这意味着尚未接收到JSON数据.
When I try exact same code in Android, I get internal server error
from the server, which means that JSON data has not been received.
我真的不明白为什么它可以在JAVA中工作,但不能在Android中工作.
I really don't understand why this is working in JAVA but not in Android.
我想达到的效果是以下命令:
The effect that I would like to achieve, is the following command:
curl --dump-header - -H "Content-Type: application/json" -X
POST --data '{"amount_adult":1, "object_id":13}'
--user travelbuddy:travelbuddy http://localhost/api/v1/purchase/
推荐答案
String authorizationString = "Basic " + Base64.encodeToString(
("travelbuddy" + ":" + "travelbuddy").getBytes(),
Base64.DEFAULT);
...
该解决方案实际上更简单:
The solution is a bit simpler actually:
String authorizationString = "Basic " + Base64.encodeToString(
("travelbuddy" + ":" + "travelbuddy").getBytes(),
Base64.NO_WRAP); // <=== Do not add '\n'
这篇关于Android-具有基本身份验证的HttpClient JSON POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!