我想提出一個Android應用程序連接到通過REST API的網絡服務,我有與內部結構的設計兩難境地。最佳的方式來建模的Android REST連接
現在我有類Client.java其purpouse是使連接服務器(ConnectionMethod是枚舉包含GET | POST值):
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:{狀態:0,結果是:陣列/ INT /串}當響應是正確的和{狀態:-1,消息:字符串}當響應不正確。
Additionaly我要讓類模型從JSON結果(User.java,Message.java ...)和用戶界面和API之間的中間部件的方法來實現應用程序和類的邏輯。
什麼是設計管理自動修正均勻的連接系統的最佳方式/失敗響應和獨立模式(用戶,消息)?
不要打擾,請使用Retrofit http://square.github.io/retrofit/ –