Android Retrofit2网络框架使用

本文详细介绍了如何使用Retrofit2进行GET和POST请求,包括配置Retrofit、定义接口、处理响应等步骤,以及使用form-data上传文件的示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

maven库

    implementation 'com.google.code.gson:gson:2.8.6'
    implementation 'com.squareup.okhttp3:logging-interceptor:4.3.0'
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava2:2.9.0'
    implementation 'com.squareup.retrofit2:adapter-rxjava:2.1.0'
    implementation 'com.squareup.okhttp3:okhttp-urlconnection:3.2.0'
    implementation 'io.reactivex.rxjava2:rxjava:2.2.20'
    implementation 'io.reactivex.rxjava2:rxandroid:2.1.1'
    implementation 'io.reactivex:rxandroid:1.2.1'
    implementation 'io.reactivex:rxjava:1.2.1'

 

1、基础使用

  a、Retrfit2的GET请求

 第一步,配置Retrfit的基本配置

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://gc.ditu.aliyun.com/")//服务端共用的baseUrl
                .addConverterFactory(GsonConverterFactory.create())//如果将服务端返回的json格式转为JavaBean,需要添加这一行代码
                .build();
        Api api = retrofit.create(Api.class);
        Map<String,String> map = new HashMap<>();
        map.put("a","郑州市");
        Call<UserBean> call = api.getUserinfoMap(map);//第一种map传参
        //Call<UserBean> call = api.getUserinfo("郑州市");//第二种直接传参
        //Call<UserBean> call = api.getUser();//第三种直接写死参数
        call.enqueue(new Callback<UserBean>() {
            @Override
            public void onResponse(Call<UserBean> call, Response<UserBean> response) {
                UserBean userBean = response.body();
                Log.e("TAG", userBean.toString());
                showToast(userBean.toString());
            }

            @Override
            public void onFailure(Call<UserBean> call, Throwable t) {
                Log.e("TAG", t.toString());
                showToast(t.toString());
            }
        });

第二步配置接口地址

public interface Api {

    /**
     * 第一种GET传参写法(参数直接写死)
     * a  :  参数名
     * city  :  传进来的值是参数值
     */
    @GET("geocoding")
    Call<UserBean> getUserinfo(@Query("a") String city);

    /**
     * 第二种GET传参写法(参数写活)
     */
    @GET("geocoding?a=郑州市")
    Call<UserBean> getUser();

    /**
     * 第三种GET传参方式(用map写活)
     * */
    @GET("geocoding")
    Call<UserBean> getUserinfoMap(@QueryMap Map<String, String> map);

}

第三步添加Javabean

public class UserBean {


    /**
     * lon : 120.58531
     * level : 2
     * address :
     * cityName :
     * alevel : 4
     * lat : 31.29888
     */

    private double lon;
    private int level;
    private String address;
    private String cityName;
    private int alevel;
    private double lat;

    public double getLon() {
        return lon;
    }

    public void setLon(double lon) {
        this.lon = lon;
    }

    public int getLevel() {
        return level;
    }

    public void setLevel(int level) {
        this.level = level;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getCityName() {
        return cityName;
    }

    public void setCityName(String cityName) {
        this.cityName = cityName;
    }

    public int getAlevel() {
        return alevel;
    }

    public void setAlevel(int alevel) {
        this.alevel = alevel;
    }

    public double getLat() {
        return lat;
    }

    public void setLat(double lat) {
        this.lat = lat;
    }

    @Override
    public String toString() {
        return "UserBean{" +
                "lon=" + lon +
                ", level=" + level +
                ", address='" + address + '\'' +
                ", cityName='" + cityName + '\'' +
                ", alevel=" + alevel +
                ", lat=" + lat +
                '}';
    }
}

2、Retrofit2的post使用

第一步配置Retrofit

Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://fanyi.youdao.com/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        Api api = retrofit.create(Api.class);
        Call<InfoBean> beanCall = api.postInfo("你好");
        beanCall.enqueue(new Callback<InfoBean>() {
            @Override
            public void onResponse(Call<InfoBean> call, Response<InfoBean> response) {
                showToast(response.body().getTranslateResult().get(0).get(0).toString());
            }

            @Override
            public void onFailure(Call<InfoBean> call, Throwable t) {
                Log.e("TAG", t.toString());
                showToast(t.toString());
            }
        });

第二步创建接口

/**
     * 第一种POST传参
     */
    @POST("translate?doctype=json&jsonversion=&type=&keyfrom=&model=&mid=&imei=&vendor=&screen=&ssid=&network=&abtest=")
    @FormUrlEncoded
    Call<InfoBean> postInfo(@Field("i") String targetSentence);

 

3、form-data表单post提交文件携带参数上传

   1)、创建接口

@POST("xxx")
Observable<LogBean> postLog(@Body RequestBody body);

2、具体上传操作

Api api = RetrofitClint.getApi();
File file = new File(file);
RequestBody requestBody = new MultipartBody.Builder().setType(MultipartBody.FORM)
        .addFormDataPart("key1", "value1")//参数1
        .addFormDataPart("key2", "value2")//参数2
        .addFormDataPart("filedata", file.getName(), RequestBody.create(MediaType.parse("multipart/form-data"), file))
                .build();
        Observable<LogBean> observable = api.postLog(requestBody);//第二种直接传参
        Subscription subscription = observable.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<LogBean>() {
                    @Override
                    public void onCompleted() {
                    }

                    @Override
                    public void onStart() {
                        super.onStart();
                    }

                    @Override
                    public void onError(Throwable e) {
                        Logger.d(TAG, "334-e:" + e.toString());
                        if (listener != null) {
                            listener.onError(e.toString());
                        }
                    }

                    @Override
                    public void onNext(LogBean bean) {
                        if (bean != null) {
                            Logger.d(TAG, "bean:" + bean.toString());
                            if (listener != null) {
                                listener.onSuccess(bean);
                            }
                        }
                    }
                });

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

落魄的Android开发

感谢支持

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值