Android中使用Retrofit的五种请求方式案例

说明沿用上一次网络请求接口接口文档说明请求方式请求参数请求地址GET 方式,无参数GET无/user/getUserGET方式,Int参数GETInt(id)/user/getParamUserPost方式,无参数POST无/user/postNoParamUserPost方式,有参数POSTInt(id)/user/postParamUserPost方式,Json化参数POSTObject(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'123注意:这里不能导入OkHttp与Gson,Retrofit内部已经包含这两个框架,否则会导致版本冲突。2.打开网络权限<uses-permission android:name="android.permission.INTERNET"></uses-permission>1在 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>12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849

准备工作Retrofit retrofit = new Retrofit.Builder()                /*必须以  '/'  结束*/                .baseUrl("你的接口地址 以 / 结尾")                /*将返回的数据转换为Gson*/                .addConverterFactory(GsonConverterFactory.create())                .build();        /* 需要写一个专门的接口类 */        apiService = retrofit.create(ApiService.class);12345678910三、GET请求网址(例如:http://www.gumenghua.com/)1.无参GET请求接口,注意:注解必须写入参数,没有参数时可以使用 . 或 ///没有数据就填 '.' 或者 '/'    @GET("getUser")    Call<User> getUser();123代码实现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) {                    }                });                12345678910111213

2.有参GET请求接口,GET请求的参数使用@Query注解/*有参GET请求 */    @GET("getParamUser")    Call<User>getParamUser(@Query("id") int id);1234apiService.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) {                    }                });123456789101112

四、POST请求1.无参POST请求接口/*无参POST请求 */    @POST("postNoParamUser")    Call<User>postNoParamUser();123apiService.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) {                    }                });123456789101112

2.有参POST请求MPI与OpenMP实验报告及源程序发送表单化参数,必须要带上注解@FormUrlEncoded且,参数必须带上参数@Field注解/*有参POST请求 */    @FormUrlEncoded    @POST("postParamUser")    Call<User> postParamUser(@Field("id") int id);1234apiService.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) {                    }                });123456789101112

3.发送Json化POST请求使用Json化参数 必须去掉注解@FormUrlEncoded且,参数中必须使用@Body注解/*JSON化参数POST请求 */    @POST("postObjectParamUser")    Call<User>postObjectParamUser(@Body User user);123 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) {                    }                });123456789101112131415161718

四、代码总结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;        }    }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145ApiService请求接口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);}123456789101112131415161718192021222324252627282930313233343536User实体类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 + '\'' +                '}';    }

(0)

相关推荐