Retrofit2+Okhttp3网络请求

权限

<uses-permission android:name="android.permission.INTERNET"></uses-permission>

//retrofit2

 api 'com.squareup.retrofit2:retrofit:2.2.0'
 api 'com.squareup.okhttp3:okhttp:3.2.0'
 api 'com.squareup.retrofit2:converter-gson:2.2.0'
 api 'com.squareup.okhttp3:logging-interceptor:3.4.2'

接口类ApiService.java

 public interface ApiService {
    	//登录接口
        @POST("api/appclient/v1/user/login")
        Call<DataResponse<LoginBean>> login(@Body Map<String, String> params);
    
        @GET("/api/appclient/v1/user/logout")
        Call<DataResponse> loginOut();
 }

封装类Api.java:
一、常用情况

public class Api {
    private static Api instance;
    private Retrofit retrofitNew;

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

    private Api() {
	      init();
    }
    
private void init(){
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        HeaderInterceptor headerInterceptor = new HeaderInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
//                .addInterceptor(headerInterceptor)
//                .addInterceptor(new HeaderInterceptor())
//                .connectTimeout(100, TimeUnit.SECONDS)
//                .writeTimeout(100, TimeUnit.SECONDS)
//                .readTimeout(100, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .build();
        retrofitNew = new Retrofit.Builder()
                .baseUrl(HttpUrl.getBaseUrl())
                .client(okHttpClient)
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    public  <T> T create(Class<T> clazz) {
        return retrofitNew.create(clazz);
    }

}

二、动态设置baseUrl

public class Api {
    private static Api instance;
    private Retrofit retrofitNew;

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

 public void setApi(){
        Log.d("apiTest", "url=="+SERVER_URL);
        retrofitNew = new Retrofit.Builder()
                .baseUrl(SERVER_URL)
                .client(getClient())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }
    
private OkHttpClient getClient(){
        HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        HeaderInterceptor headerInterceptor = new HeaderInterceptor();
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .addInterceptor(loggingInterceptor)
                .addInterceptor(headerInterceptor)
//                .addInterceptor(new HeaderInterceptor())
//                .connectTimeout(100, TimeUnit.SECONDS)
//                .writeTimeout(100, TimeUnit.SECONDS)
//                .readTimeout(100, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .build();
        return okHttpClient;
    }

   public  <T> T create(Class<T> clazz){
        if (retrofitNew == null){
            setApi();
        }
        return retrofitNew.create(clazz);
    }

使用:

若采用第二种动态设置服务器地址,网络请求前须先设置baseUrl:
Api.getInstance().setApi();

private void requestData(String name, String password) {

        Map<String, String> params = new HashMap<>();
        params.put("userName", name);
        params.put("password", password);
        Api.getInstance().create(ApiService.class).login(params).enqueue(new Callback<DataResponse<LoginBean>>() {
            @Override
            public void onResponse(Call<DataResponse<LoginBean>> call, Response<DataResponse<LoginBean>> response) {
                Log.d("networkTest", "success, response==");
                if (response.body() != null && response.body().getData() != null) {
                    Constant.token[0] = response.body().getData().getToken();
                    SharedPreferencesUtil.getInstance().putString("username", name);
                    SharedPreferencesUtil.getInstance().putString("password", password);
                    startMainActivity();
                    reqBaiduRecognizePrepare();//登录成功,异步请求百度车牌失败token
                }else {
                    Toast.makeText(getApplicationContext(),response.message(),Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<DataResponse<LoginBean>> call, Throwable t) {
                Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                bt_login.setEnabled(true);
                bt_login.setText("登录");
                Log.d("networkTest", "failed, t-->"+t.toString());
                Log.d("networkTest", "failed, t-->message=="+t.getMessage());
                Log.d("networkTest", "failed, t-->cause=="+t.getCause());
                t.printStackTrace();
            }
        });
    }

demo可参考:https://blog.youkuaiyun.com/qq_34261214/article/details/80621320

Rxjava2+okhttp3+Retrofit2使用
可参考:https://blog.youkuaiyun.com/qq_41673194/article/details/80339709

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值