Android - 具有基本身份验证的HttpClient JSON POST

时间:2012-09-15 22:43:52

标签: json httpclient

我正在尝试在JSON上通过基本身份验证接受身体JSON的网址实施一条简单的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 个答案:

答案 0 :(得分:27)

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'

答案 1 :(得分: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);

轻松修复但很难找到; - )

答案 2 :(得分:2)

我认为最简单的方法是:

postMethod.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(user, pass), "UTF-8", false));

答案 3 :(得分:0)

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