Retrofit2.0 + Okhttp3.0获取接口原生数据

public interface ApiService {
        @Multipart
        @POST("/mm/xxx")
        Call<ResponseBody> uploadImage(@Part MultipartBody.Part file);

        @FormUrlEncoded
        @POST("/mm/xxx")
        Call<ResponseBody> post(@FieldMap TreeMap<String,String> map);
    }
public void test(){
        Retrofit build = new Retrofit.Builder()
                .baseUrl("http://140.28.115.161/")
                .build();

//        RequestBody requestFile = RequestBody.create(MediaType.parse("multipart/form-data"), logFile);
//        MultipartBody.Part body = MultipartBody.Part.createFormData("uploaded_file", logFile.getName(), requestFile);
        TreeMap<String,String> treeMap = new TreeMap<>();
        treeMap.put("userId", "182683141");
        Call<ResponseBody> stringCall = build.create(ApiService.class).post(treeMap);
        stringCall.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(@NonNull Call<ResponseBody> call, @NonNull Response<ResponseBody> response) {
                try {
                    ResponseBody body = response.body();
                    assert body != null;
                    // 这样就获取到接口返回的原生json字符串了
                    String trim = body.string().trim();
                    LogUtil.e("FileLogCatUtils"," trim = " + trim);
                }catch (Exception e){
                    e.printStackTrace();
                }
                LogUtil.e("FileLogCatUtils"," call = " + call + " response = " + response);
                LogUtil.e("FileLogCatUtils"," ThreadName = " + Thread.currentThread().getName());
            }

            @Override
            public void onFailure(@NonNull Call<ResponseBody> call, @NonNull Throwable t) {
                LogUtil.e("FileLogCatUtils"," call = " + call + " Throwable = " + t);
            }
        });
    }

猜你喜欢

转载自blog.csdn.net/pengyu1801/article/details/79654283
今日推荐