1. 程式人生 > >rxjava&retrofit請求直接返回string

rxjava&retrofit請求直接返回string

1.新增gradle依賴:  
  
compile com.squareup.retrofit2:converter-scalars:2.0.0'  
2.更換轉換器  
mRetrofit = Retrofit.Builder()  
                .baseUrl(HttpAddress.SITE)  
                .addConverterFactory(ScalarsConverterFactory.create())  
                .build();  
3.定義返回型別為string  
  
new Callback<String>() {  
            @Override  
            
public void onResponse(Call<String> call, retrofit2.Response<String> response) { Log.d("debug", response.body()); } @Override public void onFailure(Call<String> call, Throwable t) { } } 注意或者不加轉換器但是Call
<ResponseBody>型別必須是ResponseBody Retrofit retrofit = new Retrofit.Builder() .baseUrl(HttpMethods.BASE_URL) // .addConverterFactory(ScalarsConverterFactory.create()) .build(); MovieService service = retrofit.create(MovieService.class); Call<ResponseBody> call = service.getTopMovie2(0, 20); call.enqueue(
new Callback<ResponseBody>() { @Override public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) { if (response.isSuccess()) { Log.i(TAG, "response.isSuccess()"); try { Log.i(TAG, "onResponse: " + response.body().string()); } catch (IOException e) { e.printStackTrace(); } } } @Override public void onFailure(Call<ResponseBody> call, Throwable t) { Log.i(TAG, "onFailure: " + t.getMessage()); } }); } public interface MovieService { @GET("top250") rx.Observable<HttpResult<List<Subject>>> getTopMovie(@Query("start") int start, @Query("count") int count); @GET("top250") Call<ResponseBody> getTopMovie2(@Query("start") int start, @Query("count") int count); }


舉例:
Call<ResponseBody> call = ApiFactory.getInstance().getApiService().updateItems2(accessToken, "cart", cart_params);
call.enqueue(new Callback<ResponseBody>() {
@Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
if (response.isSuccessful()) {
LogUtil.i("response.isSuccess()");
try {
String responseStr = response.body().string();
LogUtil.i("onResponse,onResponse=" + responseStr);
JSONObject jsonObject = new JSONObject(responseStr);
LogUtil.i("onResponse,msg=" + jsonObject.getString("msg"));
} catch (Exception e) {
e.printStackTrace();
}
}
}

@Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
LogUtil.i("onResponse,onFailure=" + t.getMessage());
}
});