retrofit

Retrofit

一.引入依赖

  implementation 'com.squareup.retrofit2:retrofit:2.7.1'
  implementation 'com.squareup.retrofit2:converter-gson:2.7.1'
  implementation 'com.squareup.okhttp3:logging-interceptor:3.6.0'

1.0

首先创建我们的接口

public interface API {
    // get方法  Call<实体类> 接口名
    @GET("get/text")
    Call<JsonResultBean> getJson();

    // 带参数的,如果是参数少可以用@Query("参数名") String 参数值
    @GET("/get/param")
    Call<GetWithParamsBean> getWithParams(@Query("keyword") String keyword,
                                          @Query("page") int page,
                                          @Query("order") String order);
    // 如果参数多可以用QueryMap  
    @GET("/get/param")
    Call<GetWithParamsBean> getWithParams(@QueryMap Map<String,Object> params);

    // post
    @POST("/post/string")
    Call<PostWithParamsBean> postWithParams(@Query("string") String content);

    // post
    @POST
    Call<PostWithParamsBean> postWithUrl(@Url String url);

    // postJsonObject 传递对象  PostWithJsonObjectBean
    @POST("/post/comment")
    Call<PostWithJsonObjectBean> postJsonObjet(@Body CommentItemBean itemBean);

    // 上传文件,文件可以包括 图片 、 视频、音频 @Part注解,要跟@Multipart注解一起使用
    @Multipart
    @POST("/api/AppAniImgType/UploadToAliyun")
    Call<FileUploadResult> postFile(@HeaderMap Map<String,Object> headers,@Part MultipartBody.Part file);
    }
    

1.1

##新建一个单例功我们所有页面使用的网络请求-包含我们的baseUrl

public class RetrofitManager {
    // 我们的baseUrl
    public static String BASE_URL="http://xxxxx/";

    //设置超时时间
    public static final int CONNECT_TIME_OUT = 100000;
    private static RetrofitManager sRetrofitManager = null;
    private Retrofit mRetrofit;

    private RetrofitManager() {
        createRetrofit();
    }

    private void createRetrofit() {
        //设置一下okHttp的参数
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .connectTimeout(CONNECT_TIME_OUT, TimeUnit.MILLISECONDS)

                .build();
        mRetrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())// 转换器直接转换成了bean类
                .build();
    }

    public static RetrofitManager getInstance() {
        if (sRetrofitManager == null) {
            synchronized (RetrofitManager.class) {
                if (sRetrofitManager == null) {
                    sRetrofitManager = new RetrofitManager();
                }
            }
        }
        return sRetrofitManager;
    }

    public Retrofit getRetrofit() {
        return mRetrofit;
    }

}

##二. 在我们的页面中使用

    private API mApi;
    
    在onCreate()方法中调用
    mApi = RetrofitManager.getInstance().getRetrofit().create(API.class);
    
    /*
    * get方法请求网路
    * */
    public void getClickRequest(View view) {
        Call<JsonResultBean> task = mApi.getJson();
        task.enqueue(new Callback<JsonResultBean>() {
            @Override
            public void onResponse(Call<JsonResultBean> call, Response<JsonResultBean> response) {
                Log.i(TAG, "onResponse:----> " + response.code());
                if (response.code() == HttpURLConnection.HTTP_OK) {
                    JsonResultBean resultBean = response.body();
                    updateList(resultBean);
                }
            }

            @Override
            public void onFailure(Call<JsonResultBean> call, Throwable t) {
                Log.i(TAG, "onFailure: ---->" + t.toString());
            }
        });
    }
     /**
     * 带参数的请求
     */
    public void getClickParams(View view) {
        Call<GetWithParamsBean> task = mApi.getWithParams("大家好", 10, "10");
        task.enqueue(new Callback<GetWithParamsBean>() {
            @Override
            public void onResponse(Call<GetWithParamsBean> call, Response<GetWithParamsBean> response) {
                int code = response.code();
                Log.i(TAG, "onResponse:----> " + code);
                if (response.code() == HttpURLConnection.HTTP_OK) {
                    Log.i(TAG, "onResponse:---->" + response.body());
                }
            }

            @Override
            public void onFailure(Call<GetWithParamsBean> call, Throwable t) {
                Log.i(TAG, "onFailure: ---->" + t.toString());
            }
        });
    }
     /**
     * 带参数的用QueryMap
     */
    public void getClickParamsQueryMap(View view) {
        Map<String, Object> params = new HashMap<>();
        params.put("keyword", "搜索关键字");
        params.put("page", 10);
        params.put("order", "0");
        Call<GetWithParamsBean> task = mApi.getWithParams(params);
        task.enqueue(new Callback<GetWithParamsBean>() {
            @Override
            public void onResponse(Call<GetWithParamsBean> call, Response<GetWithParamsBean> response) {
                int code = response.code();
                Log.i(TAG, "onResponse:----> " + code);
                if (response.code() == HttpURLConnection.HTTP_OK) {
                    Log.i(TAG, "onResponse:---->" + response.body());
                }
            }

            @Override
            public void onFailure(Call<GetWithParamsBean> call, Throwable t) {
                Log.i(TAG, "onFailure: ---->" + t.toString());
            }
        });
    }
     /**
     * 带参数的用QueryMap
     */
    public void getClickParamsQueryMap(View view) {
        Map<String, Object> params = new HashMap<>();
        params.put("keyword", "搜索关键字");
        params.put("page", 10);
        params.put("order", "0");
        Call<GetWithParamsBean> task = mApi.getWithParams(params);
        task.enqueue(new Callback<GetWithParamsBean>() {
            @Override
            public void onResponse(Call<GetWithParamsBean> call, Response<GetWithParamsBean> response) {
                int code = response.code();
                Log.i(TAG, "onResponse:----> " + code);
                if (response.code() == HttpURLConnection.HTTP_OK) {
                    Log.i(TAG, "onResponse:---->" + response.body());
                }
            }

            @Override
            public void onFailure(Call<GetWithParamsBean> call, Throwable t) {
                Log.i(TAG, "onFailure: ---->" + t.toString());
            }
        });
    }
    
      /*
     * post请求,body携带字符串内容(json)
     * */
    public void postJsonObject(View view) {
        CommentItemBean itemBean = new CommentItemBean();
        itemBean.setArticleId("123456");
        itemBean.setCommentContent("这是我提交测试的评论内容...");
        // PostWithJsonObjectBean 也可以通过对象形式拿返回值
        Call<PostWithJsonObjectBean> task = mApi.postJsonObjet(itemBean);
        task.enqueue(new Callback<PostWithJsonObjectBean>() {
            @Override
            public void onResponse(Call<PostWithJsonObjectBean> call, Response<PostWithJsonObjectBean> response) {
                int code = response.code();
                Log.i(TAG, "onResponse:----> " + code);
                if (code == HttpURLConnection.HTTP_OK) {
                    Log.i(TAG, "onResponse:---->" + response.body());
                }
            }

            @Override
            public void onFailure(Call<PostWithJsonObjectBean> call, Throwable t) {
                Log.i(TAG, "onFailure: ---->" + t.toString());
            }
        });
    }
 /*
     * 拦截器的使用
     * */
    public void postJsonObject2(View view) {
        CommentItemBean itemBean = new CommentItemBean();
        itemBean.setArticleId("123456");
        itemBean.setCommentContent("这是我提交测试...");

        OkHttpClient.Builder okhttpClient = new OkHttpClient.Builder();
        HttpLoggingInterceptor looger = new HttpLoggingInterceptor();
        looger.setLevel(HttpLoggingInterceptor.Level.BODY);
        // 只在开发版本中才会记录
        if (BuildConfig.DEBUG) {
            okhttpClient.addInterceptor(looger);
        }
        okhttpClient.addInterceptor(looger);
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(RetrofitManager.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())// 转换器直接转换成了bean类
                .client(okhttpClient.build())
                .build();
        API service = retrofit.create(API.class);
        Call<PostWithJsonObjectBean> call = service.postJsonObjet(itemBean);
        call.enqueue(new Callback<PostWithJsonObjectBean>() {
            @Override
            public void onResponse(Call<PostWithJsonObjectBean> call, Response<PostWithJsonObjectBean> response) {
                int code = response.code();
                Log.i(TAG, "onResponse:----> " + code);
                if (code == HttpURLConnection.HTTP_OK) {
                    Log.i(TAG, "onResponse:---->" + response.body());
                }
            }

            @Override
            public void onFailure(Call<PostWithJsonObjectBean> call, Throwable t) {
                Log.i(TAG, "onFailure: ---->" + t.toString());
            }
        });

    }
     File file = new File("/storage/emulated/0/Download/1.jpg");
        if (!file.exists()) {
            Toast.makeText(RetrofitActivity.this, "该文件不存在", Toast.LENGTH_SHORT).show();
            return;
        }
        MediaType mediaType = MediaType.parse("image/*");
        RequestBody fileBody = RequestBody.create(mediaType, file);
        // MultipartBody.Part  和后端约定好Key,这里的partName是用file
        MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), fileBody);
        // 添加描述
//        String descriptionString = "hello, 这是文件描述";
//        RequestBody description = RequestBody.create(MediaType.parse("multipart/form-data"), descriptionString);
        HashMap<String,Object> hashMap = new HashMap<>();
        hashMap.put("authToken","08c958df-187f-4e11-973b-3495a8e8e0ae");
        hashMap.put("appKey","6f9f7cfd-a92d-45a0-8e4a-d2aa96b84b27");
        Call<FileUploadResult> task = mApi.postFile(hashMap,part);
        task.enqueue(new Callback<FileUploadResult>() {
            @Override
            public void onResponse(Call<FileUploadResult> call, Response<FileUploadResult> response) {
                int code = response.code();
                Log.i(TAG, "onResponse:----> " + code);
                if (code == HttpURLConnection.HTTP_OK) {
                    Log.i(TAG, "onResponse:---->" + response.body());
                }
            }

            @Override
            public void onFailure(Call<FileUploadResult> call, Throwable t) {
                Log.i(TAG, "onFailure: ---->" + t.toString());
            }
        });

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值