如何将 AsyncTask 转换为 Retrofit 以从 Android 中的 WCF Webservice 获取数据
Posted
技术标签:
【中文标题】如何将 AsyncTask 转换为 Retrofit 以从 Android 中的 WCF Webservice 获取数据【英文标题】:How can convert AsyncTask to Retrofit for get data from WCF Webservice in Android 【发布时间】:2015-09-29 00:30:12 【问题描述】:我有一个 WCF 网络服务,它以 JSON 格式返回 SQL Server 数据库数据,现在我正在使用 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?
【问题讨论】:
现在我的问题是如何将此 AsyncTask 类转换为 Retrofit ? ...通过重构/重写代码...问题出在哪里?你试过了吗?还是您要免费代码? 【参考方案1】:好的,首先你不会使用带有改造的异步任务。改造负责异步部分。首先你需要定义一个休息适配器。
这是一个默认的休息适配器,其中包含您的参数。
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 文档,以防您需要任何特殊的东西,例如标头或请求拦截器。
【讨论】:
以上是关于如何将 AsyncTask 转换为 Retrofit 以从 Android 中的 WCF Webservice 获取数据的主要内容,如果未能解决你的问题,请参考以下文章
AsyncTask #3 解析 JSON 对象时出错。字符串无法转换为 JSONObject
解析JSON对象的AsyncTask#3错误。 String无法转换为JSONObject
如何使用 asynctask 将图像从 android 上传到 php