Fri*_*ngo 5 android httprequest gson retrofit
我正在使用loopj async http library to make http requests,但经过研究后about android networking library我发现它retrofit比排球更好,紧固和最可靠的网络库.
我计划将我的代码更改为适合使用retrofit..
以前,我使用这种方法来制作HTTP requests:
AsyncHttpClient AHC = new AsyncHttpClient();
RequestParams param = new RequestParams();
param.put("arg1", arg1);
param.put("arg2", arg2);
AHC.post("http://xxxxx.xxx.xxxx.xxxx", param,
new AsyncHttpResponseHandler() {
@Override
public void onSuccess(String content) {
// TODO Auto-generated method stub
Run Code Online (Sandbox Code Playgroud)
我得到的内容是 json type.
我读到改造默认使用gson ..我认为这真的更快.
以前我以这种方式填充我的内部数据库:
JSONArray jArray = new JSONArray(content);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json = jArray.getJSONObject(i);
TD.CreatePostsTable(
json.getString("id")}
Run Code Online (Sandbox Code Playgroud)
这些方法将如何改造?
非常感谢!
您的发帖方法:
@POST("/users/login")
YOUR_RETURN_TYPE loginUser(@Field("arg1") String arg1,
@Field("arg2") String arg1);
Run Code Online (Sandbox Code Playgroud)
以及改造配置:
new RestAdapter.Builder()
.setEndpoint("http://your_url")
.setLogLevel(RestAdapter.LogLevel.FULL).build();
Run Code Online (Sandbox Code Playgroud)
我建议将此方法与 Retrofit 一起使用,使用 Singleton :
private Map<String, Object> restInstances = new HashMap<String, Object>();
public <T> T getRescClient(Class<T> clazz) {
T client = null;
if ((client = (T) restInstances.get(clazz.getCanonicalName())) != null) {
return client;
}
client = restAdapter.create(clazz);
restInstances.put(clazz.getCanonicalName(), client);
return client;
}
Run Code Online (Sandbox Code Playgroud)
然后这样调用:
restApiProvider.getRestClient(UserService.class).your_method()
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你 !
| 归档时间: |
|
| 查看次数: |
992 次 |
| 最近记录: |