Retrofit2+Okhttp3网络请求

权限


//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> login(@Body Map params);
    
        @GET("/api/appclient/v1/user/logout")
        Call 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 create(Class 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 create(Class clazz){
        if (retrofitNew == null){
            setApi();
        }
        return retrofitNew.create(clazz);
    }

使用:

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

private void requestData(String name, String password) {

        Map params = new HashMap<>();
        params.put("userName", name);
        params.put("password", password);
        Api.getInstance().create(ApiService.class).login(params).enqueue(new Callback>() {
            @Override
            public void onResponse(Call> call, Response> 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> 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.csdn.net/qq_34261214/article/details/80621320

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

你可能感兴趣的:(Android)