Android Rest客户端

use*_*169 5 java android apache-httpclient-4.x

我找到了很多用于请求REST API的示例,但是所有这些都让人感到困惑,有人可以向我解释一种使用http请求的方法.

我的要求是,我想通过提供用户名,密码和密钥从REST API获取数据.

我用过的是,

        HttpClient client = new DefaultHttpClient();  
        HttpPost post = new HttpPost("REST API url"); 
        post.setHeader("Content-type", "application/json");

        JSONObject obj = new JSONObject();
        obj.put("username", "un");
        obj.put("pwd", "password");
        obj.put("key","123456");

        post.setEntity(new StringEntity(obj.toString(), "UTF-8"));
        HttpResponse response = client.execute(post);
Run Code Online (Sandbox Code Playgroud)

但是响应总是为空,当使用浏览器工具通过发布相同的数据进行测试时,这些工作正常.我的方法有些问题吗?请建议我正确的方法.谢谢

Sre*_*ama 6

(1)用于开发REST客户端的Google I/O视频会话

(2)在android开发者博客中搜索

(3)https://github.com/darko1002001/android-rest-client

请在帖子之后尝试你的问题,我可以从我基于(1)和(2)开发的其他客户端共享代码片段

不要使用云到设备消息,而是使用最新的云方法与andrid应用程序开发.

有一个名为Volley的新库,它看起来比AsyncTask更好.它在开发RESTful客户端时应该很有用.


Bha*_*ani 2

我觉得你应该试试这个

HttpContext localContext = new BasicHttpContext();
HttpClient client = new DefaultHttpClient();  
HttpPost post = new HttpPost("REST API url"); 
post.setHeader("Content-type", "application/json");

JSONObject obj = new JSONObject();
obj.put("username", "un");
obj.put("pwd", "password");
obj.put("key","123456");

post.setEntity(new StringEntity(obj.toString(), "UTF-8"));
HttpResponse response = client.execute(post,localContext);
Run Code Online (Sandbox Code Playgroud)

希望这会有所帮助。