linwoain的个人blog

知我者谓我心忧,不知我者谓我何求

0%

使用Android Annotations的Rest网络通信

使用androidannotations封装通信非常简单,只要定义一个接口即可

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
package com.linwoain.androidannotationdemo.rest;
import com.linwoain.androidannotationdemo.bean.User;
import org.androidannotations.annotations.rest.Get;
import org.androidannotations.annotations.rest.Post;
import org.androidannotations.annotations.rest.Rest;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.json.GsonHttpMessageConverter;
/**
* Created by linwoain on 2015/8/27.
* Rest服务
*/
@Rest(rootUrl = "http://192.168.1.102:8080/Hello", converters = { GsonHttpMessageConverter.class})
public interface RestTest {
@Get("/post_hello?user={user}")
String getName(String user);
@Post("/get_user?name={name}")
ResponseEntity<User> getUser(String name);
}

使用此接口,只需在需要的地方定义一个该接口的实例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
    @RestService
RestTest rest;
//无需实例化,aa会自动完成实例化,然后需要在子线程中使用:
//按钮的点击事件
public void click(View view) {
getName();
}
@Background
void getName() {
// String name = rest.getName("小李");
User user=rest.getUser("王五").getBody();
LLogUtils.i(user);
showName(user.getId()+"--"+user.getName()+"---"+user.getSex());
}
@UiThread
void showName(String name) {
ToastUtil.show(name);
}
 不要忘了在清单文件中注册网络权限
1
<uses-permission android:name="android.permission.INTERNET" />
 编译时除了aa的依赖外,还要添加:
1
2
compile 'org.springframework.android:spring-android-rest-template:2.0.0.M1'
compile 'com.google.code.gson:gson:2.3.1'

因为第二个接口返回的为User对象对应的json格式,需要服务器端设置

1
Content-Type:application/json;charset=UTF-8