目录
说明
沿用上一次网络请求接口
接口入口
接口文档
说明 | 请求方式 | 请求参数 | 请求地址 |
---|---|---|---|
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(<