我正在尝试实现一个简单的 JSON
发布到接受 JSON
的 URL在 ANDROID
上具有基本身份验证的正文中.
我试过 HttpUrlConnection
但我得到 "unauthorized"
我的数据被发送到服务器。
我尝试的另一种方法是使用 HttpClient
,但现在我遇到了不同的问题。身份验证工作完美,但数据没有发送到服务器......
可以肯定的是,我在一个简单的 Java 项目(不是 Android 环境)中设置了一个小测试。
这是我用于 POST
的代码到服务器:
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 项目中的代码运行良好。
当我在 Android 中尝试完全相同的代码时,我得到
internal server error
来自服务器,这意味着尚未收到 JSON 数据。我真的不明白为什么这在 JAVA 中有效,但在 Android 中无效。
我想达到的效果是以下命令:
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);
...
解决方案实际上有点简单:
String authorizationString = "Basic " + Base64.encodeToString(
("travelbuddy" + ":" + "travelbuddy").getBytes(),
Base64.NO_WRAP); // <=== Do not add '\n'
关于json - Android - 具有基本身份验证的 HttpClient JSON POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12443050/