2012-11-15 204 views
5

我发现这么多的样本请求REST API,但都一起,混乱,可以有一个人请我解释的方式,使用HTTP请求。的Android REST客户端

我的要求是,我想通过提供用户名,PWD和一键搞定从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); 

但响应总是空而这些工作正常时,通过发布相同data.Is有些事情错了我的做法与浏览器的工具进行测试?请给我正确的方法。谢谢

回答

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); 

希望这会有所帮助。

+0

不,我试过这个,还是同样的问题。我无法获得响应数据。有人能帮助我吗?我应该使用UrlConnection而不是Http类吗? – user470169

4

你可能忘了互联网的权限添加到清单文件。 添加以下行。

​​
6

(1)Google I/O video session for developing REST clients

(2)在Android开发者博客搜索

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

请之后尝试发布您的问题, 我可以从共享的代码片段我的休息客户开发出基于(1)&(2)

不要使用云来设备消息传递,而是使用最新的云方法和andrid应用程序开发。

有一个叫做Volley的新库,它比AsyncTask好看。它在开发RESTful客户端应该很有用。

0

无论如何,服务器是否期望对此操作发出GET请求?如果是这样,你可能想使用HttpGet而不是HttpPost。