目錄
- 說明
- 一、環境搭建
- 1.匯入依賴
- 2.打開網路權限
- 二、布局
- 三、GET請求
- 1.無參GET請求
- 2.有參GET請求
- 四、POST請求
- 1.無參POST請求
- 2.有參POST請求
- 3.發送Json化POST請求
- 四、代碼總結
說明
沿用上一次網路請求介面
介面入口
介面檔案
| 說明 | 請求方式 | 請求引數 | 請求地址 |
|---|---|---|---|
| GET 方式,無引數 | GET | 無 | /user/getUser |
| GET方式,Int引數 | GET | Int(id) | /user/getParamUser |
| Post方式,無引數 | POST | 無 | /user/postNoParamUser |
| Post方式,有引數 | POST | Int(id) | /user/postParamUser |
| Post方式,Json化引數 | POST | Object(id,name,sex,studentId,sex,data) | /user/postObjectParamUser |
一、環境搭建
1.匯入依賴
//Retrofit(網路請求框架)
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
注意:這里不能匯入OkHttp與Gson,Retrofit內部已經包含這兩個框架,否則會導致版本沖突,
2.打開網路權限
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
在 AndroidManifest中打開網路權限 ,注意:如果請求的地址為Http協議則需要在application中加入:
android:usesCleartextTraffic=“true”
設定http為可用,默認只可以請求https請求,
二、布局
<?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"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:id="@+id/sendGetNotParam"
android:text="發送GET無參請求"
android:layout_height="wrap_content"/>
<Button
android:layout_width="match_parent"
android:id="@+id/sendGetHaveParam"
android:text="發送GET有參請求"
android:layout_height="wrap_content"/>
<Button
android:layout_width="match_parent"
android:id="@+id/sendPostNotParam"
android:text="發送POST無參請求"
android:layout_height="wrap_content"/>
<Button
android:layout_width="match_parent"
android:text="發送POST有參請求"
android:id="@+id/sendPostHaveParam"
android:layout_height="wrap_content"/>
<Button
android:layout_width="match_parent"
android:text="發送POSTJson化請求"
android:id="@+id/sendPostJsonParam"
android:layout_height="wrap_content"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="24sp"
android:id="@+id/main_text"
android:layout_marginTop="20dp"
android:text="Hello World!" />
</LinearLayout>

準備作業
Retrofit retrofit = new Retrofit.Builder()
/*必須以 '/' 結束*/
.baseUrl("你的介面地址 以 / 結尾")
/*將回傳的資料轉換為Gson*/
.addConverterFactory(GsonConverterFactory.create())
.build();
/* 需要寫一個專門的介面類 */
apiService = retrofit.create(ApiService.class);
三、GET請求
1.無參GET請求
介面,注意:注解必須寫入引數,沒有引數時可以使用 . 或 /
//沒有資料就填 '.' 或者 '/'
@GET("getUser")
Call<User> getUser();
代碼實作
apiService.getUser().enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
User user = response.body();
mainText.setText(user.toString());
}
@Override
public void onFailure(Call<User> call, Throwable t) {
}
});

2.有參GET請求
介面,GET請求的引數使用@Query注解
/*有參GET請求 */
@GET("getParamUser")
Call<User>getParamUser(@Query("id") int id);
apiService.getParamUser(2).enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
User user = response.body();
mainText.setText(user.toString());
}
@Override
public void onFailure(Call<User> call, Throwable t) {
}
});

四、POST請求
1.無參POST請求
介面
/*無參POST請求 */
@POST("postNoParamUser")
Call<User>postNoParamUser();
apiService.postNoParamUser().enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
User user = response.body();
mainText.setText(user.toString());
}
@Override
public void onFailure(Call<User> call, Throwable t) {
}
});

2.有參POST請求
發送表單化引數,必須要帶上注解@FormUrlEncoded
且,引數必須帶上引數@Field注解
/*有參POST請求 */
@FormUrlEncoded
@POST("postParamUser")
Call<User> postParamUser(@Field("id") int id);
apiService.postParamUser(13).enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
User user = response.body();
mainText.setText(user.toString());
}
@Override
public void onFailure(Call<User> call, Throwable t) {
}
});

3.發送Json化POST請求
使用Json化引數 必須去掉注解@FormUrlEncoded
且,引數中必須使用@Body注解
/*JSON化引數POST請求 */
@POST("postObjectParamUser")
Call<User>postObjectParamUser(@Body User user);
User user = new User();
user.setName("順順萌新");
user.setStudentId("123456");
user.setData("我是提示資料");
user.setSex("萌新");
user.setId(1);
apiService.postObjectParamUser(user).enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
User user = response.body();
mainText.setText(user.toString());
}
@Override
public void onFailure(Call<User> call, Throwable t) {
}
});

四、代碼總結
MainActivity代碼
package com.example.secode;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Retrofit retrofit;
private ApiService apiService;
private Button sendGetNotParam;
private Button sendGetHaveParam;
private Button sendPostNotParam;
private Button sendPostHaveParam;
private Button sendPostJsonParam;
private static final String TAG = "用戶列印資訊";
private TextView mainText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
retrofit = new Retrofit.Builder()
/*必須以 '/' 結束*/
.baseUrl("你的地址,必須以 / 結尾")
/*將回傳的資料轉換為Gson*/
.addConverterFactory(GsonConverterFactory.create())
.build();
/* 需要寫一個專門的介面類 */
apiService = retrofit.create(ApiService.class);
initView();
}
private void initView() {
sendGetNotParam = (Button) findViewById(R.id.sendGetNotParam);
sendGetHaveParam = (Button) findViewById(R.id.sendGetHaveParam);
sendPostNotParam = (Button) findViewById(R.id.sendPostNotParam);
sendPostHaveParam = (Button) findViewById(R.id.sendPostHaveParam);
sendPostJsonParam = (Button) findViewById(R.id.sendPostJsonParam);
sendGetNotParam.setOnClickListener(this);
sendGetHaveParam.setOnClickListener(this);
sendPostNotParam.setOnClickListener(this);
sendPostHaveParam.setOnClickListener(this);
sendPostJsonParam.setOnClickListener(this);
mainText = (TextView) findViewById(R.id.main_text);
mainText.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sendGetNotParam:
apiService.getUser().enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
User user = response.body();
mainText.setText(user.toString());
}
@Override
public void onFailure(Call<User> call, Throwable t) {
}
});
break;
case R.id.sendGetHaveParam:
apiService.getParamUser(2).enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
User user = response.body();
mainText.setText(user.toString());
}
@Override
public void onFailure(Call<User> call, Throwable t) {
}
});
break;
case R.id.sendPostNotParam:
apiService.postNoParamUser().enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
User user = response.body();
mainText.setText(user.toString());
}
@Override
public void onFailure(Call<User> call, Throwable t) {
}
});
break;
case R.id.sendPostHaveParam:
apiService.postParamUser(13).enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
User user = response.body();
mainText.setText(user.toString());
}
@Override
public void onFailure(Call<User> call, Throwable t) {
}
});
break;
case R.id.sendPostJsonParam:
User user = new User();
user.setName("順順萌新");
user.setStudentId("123456");
user.setData("我是提示資料");
user.setSex("萌新");
user.setId(1);
apiService.postObjectParamUser(user).enqueue(new Callback<User>() {
@Override
public void onResponse(Call<User> call, Response<User> response) {
User user = response.body();
mainText.setText(user.toString());
}
@Override
public void onFailure(Call<User> call, Throwable t) {
}
});
break;
}
}
}
ApiService請求介面
package com.example.secode;
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.Field;
import retrofit2.http.FormUrlEncoded;
import retrofit2.http.GET;
import retrofit2.http.POST;
import retrofit2.http.Query;
public interface ApiService {
/*無參GET請求 */
//沒有資料就填 '.' 或者 '/'
@GET("getUser")
Call<User> getUser();
/*有參GET請求 */
@GET("getParamUser")
Call<User>getParamUser(@Query("id") int id);
/*無參POST請求 */
@POST("postNoParamUser")
Call<User>postNoParamUser();
/*有參POST請求 */
@FormUrlEncoded
@POST("postParamUser")
Call<User> postParamUser(@Field("id") int id);
/*JSON化引數POST請求 */
@POST("postObjectParamUser")
Call<User>postObjectParamUser(@Body User user);
}
User物體類
package com.example.secode;
public class User {
private int id;
private String name;
private String studentId;
private String sex;
private String data;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStudentId() {
return studentId;
}
public void setStudentId(String studentId) {
this.studentId = studentId;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", studentId='" + studentId + '\'' +
", sex='" + sex + '\'' +
", data='" + data + '\'' +
'}';
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/192772.html
標籤:其他
上一篇:Android初學
下一篇:20201024節日快樂
