Android - HttpClient JSON POST with Basic Authentication



我正在尝试实现一个简单的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/
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'

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

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

此 Base64.encodeToString 在授权字符串的末尾附加一个额外的""。然后在服务器上,""字符后面的下一行被视为请求的正文,当然是不正确的。

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

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

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

我认为最简单的方法是:

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

我认为你不应该在网址中使用本地主机

最新更新