【你不知道的Spring,Android】- 【模仿腾讯微博api】
一:
tx weibo api如下
url
http://open.t.qq.com/api/t/show
https://open.t.qq.com/api/t/show (oauth2.0使用)
支持验证方式
oauth1.0、oauth2.0、openid&openkey
格式
xml,json
http请求方式
get
是否需要鉴权
true
请求数限制
true, 查看API调用权限说明
接口测试
点击这里测试
做简单模仿:
url
http://192.168.20.32:8080/springServer/t/show
支持验证方式
无
格式
json
http请求方式
get/post
是否需要鉴权
否
二:Server
@Controller@RequestMapping(value="/t")public class Server {@RequestMapping(value="/show")@ResponseBodypublic Map<String, Object> show(){HashMap<String, Object> map = new HashMap<String, Object>();try {map.put("errcode", 0);map.put("msg", "ok");HashMap<String, Object> data = new HashMap<String, Object>();HashMap<String, Object> user = new HashMap<String, Object>();user.put("name", "xxx");data.put("user", user);map.put("data", data);} catch (Exception e) {e.printStackTrace();}return map;}}
三:androidClient
try { HttpClient client = new DefaultHttpClient();HttpPost post = new HttpPost();post.setURI(new URI("http://192.168.20.32:8080/springServer/t/show"));List<NameValuePair> nvps = new ArrayList<NameValuePair>();nvps.add(new BasicNameValuePair("name", "你好"));nvps.add(new BasicNameValuePair("age", "34"));post.getParams().setParameter(HTTP.CONTENT_ENCODING, HTTP.UTF_8);post.getParams().setParameter(HTTP.CHARSET_PARAM, HTTP.UTF_8);post.getParams().setParameter(HTTP.DEFAULT_CONTENT_CHARSET, HTTP.UTF_8);post.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));HttpResponse response = client.execute(post);System.out.println("状态:"+response.getStatusLine());HttpEntity httpEntity = response.getEntity();String o_str = EntityUtils.toString(httpEntity);System.out.println("原始返回值:"+o_str);JSONObject obj = new JSONObject(o_str); System.out.println(obj);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}
四:结果
08-24 16:34:03.609: I/System.out(14097): [socket][/192.168.30.174:36907]
08-24 16:34:03.609: I/System.out(14097): setSoSndTimeout:0
08-24 16:34:03.648: I/System.out(14097): 状态:HTTP/1.1 200 OK
08-24 16:34:03.656: I/System.out(14097): 原始返回值:{"data":{"user":{"name":"xxx"}},"msg":"ok","errcode":0}
08-24 16:34:03.664: I/System.out(14097): {"data":{"user":{"name":"xxx"}},"msg":"ok","errcode":0}
五:下载代码
点我下载