我做了类似你的事情。
在第一步中,我使用如下 方式从webservice
POST 方法的 HTTP GET 中获取数据:AsyncTask
public class GetService extends AsyncTask<String, String, String> {
private String mRestUrl;
private ServiceCallback mCallback;
private final HttpClient Client = new DefaultHttpClient();
private String Content;
private String url;
private String Error;
private ProgressDialog barProgressDialog;
private ProgressDialog Dialog;
public GetService(String restUrl, ServiceCallback callback) {
this.mRestUrl = restUrl;
this.mCallback = callback;
this.url = restUrl;
Dialog = new ProgressDialog(AppContext.CurrentContext);
}
@Override
protected void onPreExecute() {
super.onPreExecute();
}
@Override
protected String doInBackground(String... urls) {
Content = null;
BufferedReader reader = null;
try {
StringBuilder builder = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(this.url);
HttpResponse response = client.execute(get);
int status = response.getStatusLine().getStatusCode();
if (status == 200) // sucess
{
HttpEntity e = response.getEntity();
// String data = EntityUtils.toString(e);
InputStream content = e.getContent();
reader = new BufferedReader(new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
Content = builder.toString();
} else if (status == 401) {
return "-Auth Failed Error Code 400";
} else {
return "-Error Code: " + status;
}
} catch (Exception ex) {
Error = ex.getMessage();
} finally {
Dialog.dismiss();
try {
reader.close();
}
catch (Exception ex) {
ex.printStackTrace();
}
}
return Content;
}
@Override
protected void onPostExecute(String result) {
try {
GetService.this.get(20000, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
mCallback.onTaskComplete(result);
super.onPostExecute(result);
}
}
我的回调类是:
公共抽象类ServiceCallback{
public abstract void onTaskComplete(String result);
}
我在我想从 web 服务获取数据的任何地方都在我的代码中调用 AsyncTask:
new GetService(url, new ServiceCallback() {
public void onTaskComplete(String response) {
// Parse Response of WebService
}
}).execute();
在第二步中,我在 onTaskComplete 方法中使用 json 帮助程序库(如Gson
or )解析 WebService 的响应Jackson
。例如在杰克逊:
List<YourClass> data = new ObjectMapper()
.readValue(
response,
new TypeReference<List<YourClass>>() {
});
最后,我将数据存储在数据库中。用于连接到 DB 我更喜欢GreenDao
用作我的 ORM。这样,DB中的存储数据可以在一行代码中完成,如下所示:
//after converting json to object
YourORMDaoClass.insertOrReplaceInTx(data);
要使用GreenDao
ORM ,此链接非常有用;