【发布时间】:2015-07-09 22:57:37
【问题描述】:
我正在制作一个通过 REST API 连接到 Web 服务的 Android 应用,但我对内部架构的设计感到两难。
现在我有了 Client.java 类,其目的是与服务器建立连接(ConnectionMethod 是包含 GET|POST 值的 Enum):
public class Client {
private AsyncHttpClient client = new AsyncHttpClient(); //I use com.loopj.AsyncHttpClient to connect
private ConnectionMethod method;
private RequestParams params = new RequestParams();
private AsyncHttpResponseHandler responseHandler = new JsonHttpResponseHandler(){
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
//Actions when connection success
}
@Override
public void onFailure(int statusCode, Header[] headers, JSONObject response, Throwable error) {
//Actions when connection fails
}
};
public Client (RequestParams params, ConnectionMethod method) {
this.params = params;
this.method = method;
}
public void addParameters (Map<String, String> parameters) {
for (Map.Entry<String, String> entry : parameters.entrySet()) {
this.params.put(entry.getKey(), entry.getValue());
}
}
public ServerResponse connect () {
RequestHandle handle;
if (this.method==ConnectionMethod.POST) {
handle = postRequest();
}
else {
handle = getRequest();
}
//How can I treat here different type of responses homogeneously?
}
private RequestHandle getRequest () {
return client.get(Constants.getEndpoint(), this.params, this.responseHandler);
}
private RequestHandle postRequest () {
return client.post(Constants.getEndpoint(), this.params, this.responseHandler);
}
}
从服务器请求信息的示例方法如下:
public static void login (String login, String password) {
//This classes should be static or dynamic?
Map<String, String> map = new HashMap<String, String>();
map.put("login", login);
map.put("password", password);
map.put("method", "site_login");
Client c = new Client();
c.addParameters(map);
c.getRequest();
}
所有服务器响应都是 JSON:响应正确时为 {status:0, result:array/int/string},响应不正确时为 {status:-1, message:string}。
另外,我想从 JSON 结果(User.java、Message.java...)和 UI 和 API 之间的中间方法创建类来建模组件,以实现应用程序和类的逻辑。
设计一个可自动管理正确/失败响应且独立于模型(用户、消息...)的同构连接系统的最佳方法是什么?
【问题讨论】:
-
别打扰,使用 Retrofit square.github.io/retrofit