网络通信框架之retrofit
主页: [https://github.com/square/retrofit](https://github.com/square/retrofit)
注意: 使用Retrofit的前提是**服务器端代码遵循REST规范
!!!!!**
功能:
* 效率非常高
* 可以直接将结果转换称Java类
* 主要是配合RxJava一起使用
配置:
implementation 'com.squareup.retrofit2:retrofit:2.0.2' implementation 'com.squareup.retrofit2:converter-gson:2.0.2' implementation 'com.google.code.gson:gson:2.8.5' implementation 'com.squareup.retrofit2:adapter-rxjava:2.0.2' // OkHttp3 api "com.squareup.okhttp3:okhttp:3.10.0" api "com.squareup.okhttp3:logging-interceptor:3.10.0" //网络日志 implementation('com.github.ihsanbal:LoggingInterceptor:3.0.0') { exclude group: 'org.json', module: 'json' }
HttpManager.java
package com.loaderman.demo.http; import android.os.Build; import com.ihsanbal.logging.Level; import com.ihsanbal.logging.LoggingInterceptor; import com.loaderman.demo.BuildConfig; import com.loaderman.demo.MyApplication; import java.io.File; import java.io.IOException; import okhttp3.Cache; import okhttp3.Interceptor; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; import okhttp3.internal.platform.Platform; import retrofit2.Retrofit; import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory; import retrofit2.converter.gson.GsonConverterFactory; public class HttpManager { private static HttpManager apiManager; private static final String TAG = "HttpManager"; private static final Interceptor REWRITE_CACHE_CONTROL_INTERCEPTOR = new Interceptor() { @Override public Response intercept(Chain chain) throws IOException { int maxAge = 60 * 5; // 在线缓存在5分钟内可读取 Request request = chain .request() .newBuilder() .addHeader("User-Agent", Build.BRAND + "/" + Build.MODEL + "/" + Build.VERSION.RELEASE)//添加请求头 .header("Cache-Control", "public, max-age=" + maxAge) .build(); return chain.proceed(request); } }; private static final LoggingInterceptor httpLoggingInterceptor = new LoggingInterceptor.Builder() .loggable(BuildConfig.DEBUG) .setLevel(Level.BASIC) .log(Platform.INFO) .request("Request") .response("Response") .build(); private static File httpCacheDirectory = new File(MyApplication.applicationContext.getCacheDir(), "mCache"); private static int cacheSize = 10 * 1024 * 1024; // 10 MiB private static Cache cache = new Cache(httpCacheDirectory, cacheSize); private static OkHttpClient client = new OkHttpClient.Builder() .addNetworkInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR) .addInterceptor(REWRITE_CACHE_CONTROL_INTERCEPTOR) .addInterceptor(httpLoggingInterceptor) .cache(cache) .build(); public static HttpManager getInstence() { if (apiManager == null) { synchronized (HttpManager.class) { if (apiManager == null) { apiManager = new HttpManager(); } } } return apiManager; } private static Apiservice apiservice; public Apiservice getHttpService() { if (apiservice == null) { synchronized (new Object()) { if (apiservice == null) { Retrofit retrofit = new Retrofit.Builder() .baseUrl("http://192.168.0.104:8080") .addConverterFactory(GsonConverterFactory.create()) //设置数据解析器 .addCallAdapterFactory(RxJavaCallAdapterFactory.create()) .client(client) .build(); apiservice = retrofit.create(Apiservice.class); } } } return apiservice; } }
package com.loaderman.demo.http; import com.loaderman.demo.bean.User; import java.util.List; import java.util.Map; import okhttp3.RequestBody; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.Field; import retrofit2.http.FormUrlEncoded; import retrofit2.http.GET; import retrofit2.http.Headers; import retrofit2.http.Multipart; import retrofit2.http.POST; import retrofit2.http.PUT; import retrofit2.http.Part; import retrofit2.http.Path; import retrofit2.http.Query; import retrofit2.http.QueryMap; public interface Apiservice { // Path是网址中的参数,例如:trades/{userId} // Query是问号后面的参数,例如:trades/{userId}?token={token} // QueryMap 相当于多个@Query // Field用于Post请求,提交单个数据,然后要加@FormUrlEncoded // Body相当于多个@Field,以对象的方式提交 // @Streaming:用于下载大文件 // @Header,@Headers、加请求头 // 具体查看: https://square.github.io/retrofit/ @GET("/user/user1.json") Call<User> getUser(); @POST("users/{user}/repos") Call<List<User>> listRepos(@Path("user") String user);//@Path("user") 将参数替换到UR中 例如传 zhangsan ,那么URl为:users/zhangsan/repos @GET("users/list?sort=desc") //可以对数据进行排序 Call<User> getList(); @POST("users/new") Call<User> createUser(@Body User user);//可传实体类 @Headers("Cache-Control: max-age=640000") @GET("user/list") Call<List<User>> userList(); @Multipart @PUT("user/photo") Call<User> updateUser(@Part("photo") RequestBody photo, @Part("description") RequestBody description); @FormUrlEncoded @POST("user/edit") Call<User> updateUser(@Field("first_name") String first, @Field("last_name") String last); @GET("group/{id}/users") Call<List<User>> groupList(@Path("id") int groupId, @QueryMap Map<String, String> options); @GET("group/{id}/users") Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort); }
使用:
package com.loaderman.demo; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.TextView; import android.widget.Toast; import com.loaderman.demo.bean.User; import com.loaderman.demo.http.HttpManager; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class MainActivity extends AppCompatActivity { private TextView tvMsg; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); tvMsg = findViewById(R.id.tv_msg); } public void onClick(View view) { switch (view.getId()) { case R.id.btn_get: HttpManager.getInstence().getHttpService().getUser().enqueue(new Callback<User>() { @Override public void onResponse(Call<User> call, Response<User> response) { boolean successful = response.isSuccessful(); System.out.println("isSuccessful"+ successful); if (successful){ User user = response.body(); tvMsg.setText(user.toString()); System.out.println("onResponse"+ user); Toast.makeText(MainActivity.this,user.toString(),Toast.LENGTH_LONG).show(); }else { Toast.makeText(MainActivity.this,response.code()+response.message(),Toast.LENGTH_LONG).show(); } } @Override public void onFailure(Call<User> call, Throwable t) { System.out.println("onFailure"+t.toString()); } }); break; } } }
最后,关注【码上加油站】微信公众号后,有疑惑有问题想加油的小伙伴可以码上加入社群,让我们一起码上加油吧!!!