说明
Retrofit 是OkHttp封装应用
实例
1、Retrofit 依赖库
app/build.gradle
implementation 'com.squareup.retrofit2:retrofit:2.9.0'
2、添加网络权限
app/src/main/AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"/>
3、界面布局
比较简单就一个按钮
app/src/main/res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:orientation="vertical">
<Button
android:id="@+id/btn_mian_four"
android:text="post异步请求"
android:onClick="PostAsync"
android:layout_width="200dp"
android:layout_height="50dp"
/>
</LinearLayout>
4、创建接口
主要是为了方便调用
app/src/main/java/com/pha/four_retrofit/face/HttpServices.java
package com.pha.four_retrofit.face;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;
public interface HttpServices {
// get 用Query 注解 ;post 用field注解
@GET("get")
Call<ResponseBody> Get(@Query("username") String userName, @Query("pwd") String pwd);
@POST("post")
@FormUrlEncoded
Call<ResponseBody> Post(@Field("username") String userName, @Field("pwd") String pwd);
}
5、访问网络
app/src/main/java/com/pha/four_retrofit/MainActivity.java
package com.pha.four_retrofit;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import com.pha.four_retrofit.face.HttpServices;
import java.io.IOException;
import okhttp3.ResponseBody;
import retrofit2.Retrofit;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void PostAsync(View view) {
// 1、 创建HttpServices.java
// 2、 创建Retrofit对象,并生成接口实现类对象
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://www.httpbin.org/").build();
HttpServices httpServices = retrofit.create(HttpServices.class);
// 3、传参
retrofit2.Call<ResponseBody> call = httpServices.Post("abc", "123");
call.enqueue(new retrofit2.Callback<ResponseBody>() {
@Override
public void onResponse(retrofit2.Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
try {
Log.e(TAG, "PostAsync: " +response.body().string());
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(retrofit2.Call<ResponseBody> call, Throwable t) {
}
});
}
}
知识点
- Retrofit 注解
@GET(“get”)
@Query
@POST(“post”)
@Field
@FormUrlEncoded
其中 // get 用Query 注解 ;post 用field注解 - Retrofit 创建队形
Retrofit retrofit = new Retrofit.Builder().baseUrl("http://www.httpbin.org/").build();
HttpServices httpServices = retrofit.create(HttpServices.class);