我有一个以JSON格式返回SQL Server数据库数据的WCF Web服务,现在我正在使用AsyncTask通过此代码在Android中获取此数据:
public class FetchInfo extends AsyncTask {
private String year = "94";
private String month = "1";
private String requested_column = "";
private String kodemelli = "";
public FetchInfo(String year, String month,String requested_column, String kodemelli) {
this.year = year;
this.month = month;
this.requested_column = requested_column;
this.kodemelli = kodemelli;
}
@Override
protected String doInBackground(Object[] params) {
try {
System.out.println("guru");
DefaultHttpClient httpClient=new DefaultHttpClient();
//Connect to the server
HttpGet httpGet=new HttpGet("http://SERVERIP:8005/Service1.svc/checkLogin1?year="+year+"&month="+month+"&requested_column="+requested_column+"&kode_melli="+kodemelli);
//Get the response
String result = "";
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
InputStream stream=httpEntity.getContent();
result = convertStreamToString(stream);
//Convert the stream to readable format
if (result.contains("\"error\"") || result.contains("\"server error\"")){
Main.result = "0";
MainFish.result = "0";
}else {
Main.result = result;
MainFish.result = result;
}
} catch (Exception e) {
Main.result = "error";
MainFish.result = "error";
}
return "";
}
public static String convertStreamToString(InputStream is)
{
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
}
catch (IOException e) {
e.printStackTrace();
}
finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
由此,当请求超过例如10个请求时,响应时间非常长。 从这个主题How to speed up fetching of data from server using JSON?我意识到我应该使用Retrofit而不是AsyncTask来使我的程序工作。
现在我的问题是如何将AsyncTask类转换为Retrofit?
感谢。
答案 0 :(得分:0)
好的,首先你不会在改造中使用异步任务。 Retrofit负责异步部分。首先,您需要定义一个休息适配器。
这是一个默认的rest适配器,其中包含您的参数。
public class ApiClient {
private static ApiInterface sApiInterface;
public static ApiInterface getApiClient(Context context) {
//build the rest adapter
if (sApiInterface == null) {
final RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("http://SERVERIP:8005")
.build();
sApiInterface = restAdapter.create(ApiInterface.class);
}
return sApiInterface;
}
public interface ApiInterface {
// /Service1.svc/checkLogin1?year="+year+"&month="+month+"&requested_column="+requested_column+"&kode_melli="+kodemelli
@GET("/Service1.svc/checkLogin1")
void getYourObject(
@Query("year") String year,
@Query("month") String month,
@Query("requested_column") String requested_column,
@Query("kode_melli") String kodemelli,
RetrofitCallback<YourObjectModel> callback);
}
在有了一个休息适配器后,你需要一个模型来放入数据。使用jsonschema2pojo将有效的JSON转换为POJO模型。以下是我的一个json响应及其模型的示例。
{
"id": "37",
"title": "",
"short_name": "",
"short_description": "",
"full_description": "",
"url": "http:\/\/\/shows\/programname",
"Image": {
"url": "https:\/\/s3.amazonaws.com\/image\/original\/b2mWDPX.jpg",
"url_sm": "https:\/\/s3.amazonaws.com\/image\/small\/b2mWDPX.jpg",
},
"image": "b2mWDPX.jpg",
"hosts": [{
"id": "651",
"display_name": "",
"username": "",
"Image": {
"url": "https:\/\/s3.amazonaws.com\/image\/original\/selfie.jpg",
"url_sm": "https:\/\/s3.amazonaws.com\/image\/small\/selfie.jpg",
}
}],
"airtimes": [{
"start": "11:00:00",
"end": "13:30:00",
"weekday": "6"
}],
"categories": [{
"id": "84",
"title": "Bluegrass",
"short_name": "bluegrass"
}],
"meta": []
}
我得到这个模型。和其他一些人一起去。
public class Program {
@Expose
private doublea.models.Airtime Airtime;
@Expose
private String id;
@Expose
private String title;
@SerializedName("short_name")
@Expose
private String shortName;
@SerializedName("full_description")
@Expose
private String fullDescription;
@SerializedName("short_description")
@Expose
private String shortDescription;
@Expose
private doublea.models.Image Image;
@SerializedName("image")
@Expose
private String imageName;
@Expose
private List<Host> hosts = new ArrayList<Host>();
@Expose
private List<Category> categories = new ArrayList<Category>();
@Expose
private List<Airtime> airtimes = new ArrayList<Airtime>();
/** Getters and Setters */
public Program() {
}
然后确保你处理失败案件。
public class RetrofitCallback<S> implements Callback<S> {
private static final String TAG = RetrofitCallback.class.getSimpleName();
@Override
public void success(S s, Response response) {
}
@Override
public void failure(RetrofitError error) {
Log.e(TAG, "Failed to make http request for: " + error.getUrl());
Response errorResponse = error.getResponse();
if (errorResponse != null) {
Log.e(TAG, errorResponse.getReason());
if (errorResponse.getStatus() == 500) {
Log.e(TAG, "Handle Server Errors Here");
}
}
}
}
最后拨打api电话。
private void executeProgramApiCall(String year, String month, String requested_column, String kodemelli) {
ApiClient.getApiClient(this).getProgram(year, month, requested_column, kodemelli, new RetrofitCallback<Program>() {
@Override
public void success(YourObjectModel program, Response response) {
super.success(YourObjectModel , response);
//TODO: Do something here with your ObjectMadel
}
});
}
我强烈建议您查看retrofit文档,以防您需要任何特殊功能,例如标头或请求拦截器。 快乐的编码。