我正在尝试将一个简单的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);
Run Code Online (Sandbox Code Playgroud)
Java项目中的代码非常完美.
当我在Android中尝试完全相同的代码时,我internal server error从服务器获取,这意味着尚未收到JSON数据.
我真的不明白为什么这在JAVA中工作但在Android中不起作用.
我想要实现的效果是以下命令:
curl --dump-header …Run Code Online (Sandbox Code Playgroud)