13

我正在尝试对 URL 实现一个简单JSON的帖子,该 URLJSON在正文中接受基本身份验证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/
4

4 回答 4

28
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'
于 2012-12-13T15:16:59.480 回答
4

最后,一切都整理好了。任何可能遇到此问题的人都是解决方案。

String authorizationString = "Basic " + Base64.encodeToString(("travelbuddy" + ":" + "travelbuddy").getBytes(), Base64.DEFAULT); //this line is diffe
postMethod.setHeader("Authorization", authorizationString);

这个 Base64.encodeToString 在授权字符串的末尾附加了一个额外的“\n”。然后在服务器上的“\n”字符之后的下一行被视为请求的主体,当然是不正确的。

通过替换授权字符串中的所有新行将解决问题:

    String authorizationString = "Basic " + Base64.encodeToString(("travelbuddy" + ":" + "travelbuddy").getBytes(), Base64.DEFAULT); //this line is diffe
authorizationString.replace("\n", "");
    postMethod.setHeader("Authorization", authorizationString);

容易修复但很难找到;-)

于 2012-09-28T00:08:41.757 回答
2

I think the simplest way is:

postMethod.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(user, pass), "UTF-8", false));
于 2014-09-08T13:39:24.210 回答
0

我认为你不应该在 url 中使用 localhost

于 2012-09-19T02:42:38.773 回答