android + Spring RESTful 简单登录 (spring3实现服务端 rest api)
url?format=json 服务器端返回json数据
url?format=xml 服务器端返回xml数据
url 默认返回html数据
登录restful风格 部分源码
android客户端 导入spring for android开源jar
spring-android-rest-template-1.0.0.RC1.jar
spring-android-core-1.0.0.RC1.jar
spring-android-auth-1.0.0.RC1.jar
服务器端部分代码(spring3.1.1+hibernate4.1.2(jpa2)完全注解方式实现 )
======================================上代码=====================================
======================================android客户端=================================
- public class SpringHttpClient {
- private static RestTemplate restTemplate;
- private final static String url = "http://192.168.0.8:6060/contact";
- private final static String login = url + "/user/userLogin/{loginname},{loginpassword}?format=json";
- private final static String query = url + "/user/list?format=json";
- private final static String add = url + "/user/add?format=json";
- private final static String detail = url + "/user/{id}/detail?format=json";
- private final static String update = url + "/user/{id}/updates?format=json";
- private final static String delete = url + "/user/{id}/delete?format=json";
- private final static String upload = url + "/user/upload?format=json";
- static {
- restTemplate = new RestTemplate();
- }
- public SpringHttpClient(){
- }
- /**
- * 登录,
- * @param username
- * @param password
- * @return {"user":{"id":"1","loginname":"superman","loginpassword":"unicom","username":"超级管理员","useremail":"superman@163.com","usermobile":null,"userstate":null,"userlogintime":null}}
- */
- public static String OAuth(String username,String password){
- Map<String, String> request = new HashMap<String, String>();
- request.put("loginname", username);
- request.put("loginpassword", password);
- return getObject(login,request);
- }
- /**
- * 得到所有的用户,
- * @return ........
- */
- public static String ListAll(){
- return getObject(query, null);
- }
- /**
- * 根据id得到唯一用户
- * @param id
- * @return{"user":{"id":"4028809b376e28be01376e294b180000","loginname":"sdfsdf","loginpassword":"sdfsdf","username":"sdfsdf","useremail":"sdfsdf","usermobile":null,"userstate":null,"userlogintime":null}}
- */
- public static String Detail(String id){
- Map<String, String> request = new HashMap<String, String>();
- request.put("id", id);
- return getObject(detail, request);
- }
- /**
- * 添加一个用户
- * @param user
- * @return
- */
- public static String Add(Users user){
- Map<String, String> request = new HashMap<String, String>();
- request.put("id", "");
- MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
- map.add("loginname", user.getLoginname());
- map.add("loginpassword", user.getLoginpassword());
- map.add("useremail", user.getUseremail());
- map.add("usermobile", user.getUsermobile());
- return postObject(add,map,request);
- }
- /**
- * 根据id更新用户 返回更新的实例和信息(restTemplate.put 也可以直接更新)
- * @param id
- * @param user
- * @return{"users":{"id":"4028809b376daa8901376dab59520001","loginname":"45345345","loginpassword":null,"username":"测试一下kankan","useremail":null,"usermobile":"ddddd","userstate":null,"userlogintime":null}}
- */
- public static String Update(String id,Users user){
- Map<String, String> request = new HashMap<String, String>();
- request.put("id", id);
- MultiValueMap<String, String> map = new LinkedMultiValueMap<String, String>();
- map.add("loginname", user.getLoginname());
- map.add("username", user.getUsername());
- map.add("usermobile", user.getUsermobile());
- return postObject(update,map, request);
- }
- /**
- * 更加id删除用户(也可以用restTemplate.delete 但是没有返回的信息)
- * @param id
- * @param user
- * @return {"ajax":{"success":true,"messages":"删除成功!"}}
- */
- public static String Delete(String id){
- Map<String, String> request = new HashMap<String, String>();
- request.put("id", id);
- return getObject(delete, request);
- }
- /**
- * 上传文件
- * @param path
- * @return
- */
- public static String UploadFile(String path){
- MultiValueMap<String, Object> formData = new LinkedMultiValueMap<String, Object>();
- Resource resource;
- try {
- resource = new UrlResource("file://"+path);
- formData.add("json", resource);
- } catch (MalformedURLException e) {
- e.printStackTrace();
- }
- HttpHeaders requestHeaders = new HttpHeaders();
- requestHeaders.setContentType(MediaType.MULTIPART_FORM_DATA);
- HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<MultiValueMap<String, Object>>(formData, requestHeaders);
- ResponseEntity<String> response = restTemplate.exchange(upload, HttpMethod.POST, requestEntity, String.class);
- return response.getBody();
- }
=============================服务器端部分代码==============================
- /**注意下面的方法中请求的方法名称是一样的,
- * 只不过根据不同的RequestMethod.GET来找对应的方法
- * RequestMethod (
- * GET=get提交,
- * HEAD,
- * POST=post提交,
- * PUT=put更新,
- * DELETE=delete删除,
- * OPTIONS, TRACE)
- * 对应
- * <form:form method="POST">
- * <form:form method="PUT">
- * <form:form method="DELETE">
- */
- /**
- * 用户列表例子(不带分页)
- * @return
- */
- @RequestMapping(value="/list",method=RequestMethod.GET)
- public ModelAndView UserList(){
- List<Users> list = usersService.listAll();
- return new ModelAndView("main", "userslist", list);
- }
- /**
- * 用户列表例子(带分页)
- * @return
- */
- @RequestMapping(value="/query",method=RequestMethod.GET)
- public ModelAndView UserListPage(HttpServletRequest request,Model model, @ModelAttribute("command") Users command){
- model.addAttribute(Constants.COMMAND, command);
- int pn = ServletRequestUtils.getIntParameter(request, "pn", 1);
- Page<Users> list = usersService.listAllUsers(command, pn);
- model.addAttribute("page", list);
- return new ModelAndView("query");
- }
- /**
- * 新增之前绑定PO到form表单跳转到新增页面例子
- * @param model
- * @return
- */
- @RequestMapping(value="/add",method=RequestMethod.GET)
- public ModelAndView before_UserAdd(Model model){
- //相当于request.setattribute的意思
- if(!model.containsAttribute(Constants.COMMAND))
- model.addAttribute(Constants.COMMAND, new Users());
- return new ModelAndView("add");
- }
- /**
- * 新增用户例子
- * @param users
- * @return
- */
- @RequestMapping(value="/add",method=RequestMethod.POST)
- public ModelAndView after_UserAdd(Users user){
- usersService.save(user);
- AjaxResponse ajax = new AjaxResponse();
- ajax.setSuccess(true);
- ajax.setMessages("注册成功!");
- return new ModelAndView("ajax","ajax",ajax);
- //也可以直接返回列表也行
- //return new ModelAndView(new RedirectView("list"));
- }
- /**
- * 更新之前绑定PO到form表单跳转到更新页面
- * @param id
- * @param model
- * @return
- */
- @RequestMapping(value="/{id}/detail",method=RequestMethod.GET)
- public ModelAndView get_Users(@PathVariable String id,Model model){
- Users users = usersService.get(id);
- model.addAttribute("users", users);
- return new ModelAndView("detail");
- }
- /**
- * 更新之前绑定PO到form表单跳转到更新页面
- * @param id
- * @param model
- * @return
- */
- @RequestMapping(value="/{id}/updates",method=RequestMethod.GET)
- public ModelAndView before_UsersUpdate(@PathVariable String id,Model model){
- Users users = usersService.get(id);
- if(!model.containsAttribute(Constants.COMMAND))
- model.addAttribute(Constants.COMMAND, users);
- return new ModelAndView("updates");
- }
- /**
- * 更新用户例子(put更新 一般用在web)
- * @param users
- * @return
- */
- @RequestMapping(value="/{id}/updates",method=RequestMethod.PUT)
- public ModelAndView after_put_UserUpdate(Users user){
- usersService.update(user);
- return new ModelAndView("redirect:../list");
- }
- /**
- * 更新用户例子(post更新 一般用在client)
- * @param users
- * @return
- */
- @RequestMapping(value="/{id}/updates",method=RequestMethod.POST)
- public ModelAndView after_post_UserUpdate(Users user){
- usersService.update(user);
- AjaxResponse ajax = new AjaxResponse();
- ajax.setSuccess(true);
- ajax.setMessages("更新成功!");
- return new ModelAndView("ajax","ajax",ajax);
- }
- /**
- * 删除用户例子
- * @param id
- * @return
- */
- @RequestMapping(value="/{id}/delete",method=RequestMethod.GET)
- public ModelAndView UserDelete(@PathVariable String id){
- usersService.delete(id);
- AjaxResponse ajax = new AjaxResponse();
- ajax.setSuccess(true);
- ajax.setMessages("删除成功!");
- return new ModelAndView("ajax","ajax",ajax);
- }
- /**
- * 上传文件
- * @param request
- * @return
- */
- @RequestMapping(value="/upload",method=RequestMethod.POST)
- public ModelAndView Upload(@RequestParam("json") MultipartFile multi){
- try {
- byte[] bytes = multi.getBytes();
- FileOutputStream out = new FileOutputStream("D:\\"+multi.getOriginalFilename());
- out.write(bytes);
- out.close();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- AjaxResponse ajax = new AjaxResponse();
- ajax.setSuccess(true);
- ajax.setMessages("文件上传成功!");
- return new ModelAndView("ajax","ajax",ajax);
- }
//--------------------------------------------------------------
使用Spring-Android获取和解析json数据
spring-android-core-1.0.0.M4.jar
spring-android-rest-template-1.0.0.M4.jar
gson-2.1.jar 使用google的这个json解析lib是因为这个lib较小
服务端返回数据如:
- {"id":"109","word":"test","translation":"n. 试验;检验"}
客户端建立对应的Domain类,如:
- public class Word {
- private int id;
- private String word;
- private String translation;
- }
使用Spring-Android调用,并转换成Word类
- String url = "http://localhost/api/word/detail.php?id=109";
- RestTemplate restTemplate = new RestTemplate();
- Word word = restTemplate.getForObject(url, Word.class);
另外Spirng Android的Lib库中还提供了解析XML,RSS,还有OAuth验证的实现。
//--------------------------------------------------------------------------------------
http://www.chenwg.com/android/spring-android%E7%9A%84%E4%BD%BF%E7%94%A8.html
了解J2EE的人都会知道spring这个开源框架,不过哥对J2EE的开发没什么兴趣,太重量级了,不适合互联网的应用,还是喜欢php多点,不过sping在移动开发这块也推出了spring-android,spring-android可以做什么?有什么优势呢?
spring-android主要提供了两个重要的功能:
1.Rest模板,很多Android应用都要与服务器进行交互,而现在很多互联网应用的服务器端都会提供Rest服务,数据格式一般是json、xml、rss等,如果使用spring-android,这将大大方便你的Android应用与服务器端的交互,spring-android在解析json,xml都是非常方便的;
2.Auth授权验证,现在很多互联网应用都提供了开放的API服务,而你的Android应用要接入到这些服务中去,往往要经过授权才行,现在很多应用都使用Auth授权认证,如twitter、facebook、新浪微博等,如果使用spring-android,在授权验证这块将会非常方便。
如何使用spring-android呢?
1.首先要去http://www.springsource.org/spring-android 下载spring-android,然后解压。
2.新建一个Android项目,然后将解压后的spring-android里的spring-android-core-1.0.1.RELEASE.jar和spring-android-rest-template-1.0.1.RELEASE.jar放到Android项目的lib目录下,因为要访问在网络,所以要在AndroidManifest.xml文件下加入<uses-permission android:name=”android.permission.INTERNET”/>
3.acitivity_main.xml文件如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
android:layout_width
=
"match_parent"
android:layout_height
=
"match_parent"
>
<
TextView
android:id
=
"@+id/result_text"
android:layout_width
=
"wrap_content"
android:layout_height
=
"wrap_content"
android:layout_centerHorizontal
=
"true"
android:layout_centerVertical
=
"true"
tools:context
=
".MainActivity"
/>
</
RelativeLayout
>
|
4.MainActivity.java如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
|
package
com.hxxy.springforandroidfirstdemo;
import
org.springframework.http.converter.StringHttpMessageConverter;
import
org.springframework.web.client.RestTemplate;
import
android.app.Activity;
import
android.os.AsyncTask;
import
android.os.Bundle;
import
android.widget.TextView;
public
class
MainActivity
extends
Activity {
@Override
public
void
onCreate(Bundle savedInstanceState) {
super
.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final
TextView resultTextView = (TextView) findViewById(R.id.result_text);
AsyncTask<String, Void, String> simpleGetTask =
new
AsyncTask<String, Void, String>() {
@Override
protected
String doInBackground(String... params) {
// executed by a background thread
// 创建一个RestTemplate实例
RestTemplate restTemplate =
new
RestTemplate();
// 添加字符串消息转换器
restTemplate.getMessageConverters().add(
new
StringHttpMessageConverter());
return
restTemplate.getForObject(params[
0
], String.
class
);
}
@Override
protected
void
onPostExecute(String result) {
resultTextView.setText(result);
}
};
// 完成时更新resultTextView
simpleGetTask.execute(url);
}
}
|