📌  相关文章
📜  如何在Android中使用Retrofit将数据发布到API?

📅  最后修改于: 2021-05-13 15:10:13             🧑  作者: Mango

我们已经在Android Studio的Android应用中看到了从API读取数据的信息。为了从API读取数据,我们使用GET请求读取JSON格式的数据。在本文中,我们将研究如何在Android Studio的Android应用程序中向REST API添加数据。

我们将在本文中构建什么?

我们将构建一个简单的应用程序,在该应用程序中,我们将使用带有POST请求的Retrofit库将数据添加到REST API中。我们将通过编辑文本字段添加数据,并通过响应代码验证我们的数据是否已添加到API。当我们向API添加数据时,我们将看到201作为响应代码。 201响应代码表示已将数据添加到我们的API。下面提供了一个示例视频,以使您对本文中的工作有个大概的了解。注意,我们将使用Java语言实现该项目。

数据可以以XML格式和JSON等不同格式添加到API。大多数API以JSON格式发布其数据。因此,我们还将以JSON对象的形式将数据发布到我们的API。

分步实施

步骤1:创建一个新项目

要在Android Studio中创建新项目,请参阅如何在Android Studio中创建/启动新项目。请注意,选择Java作为编程语言。

步骤2:在您的build.gradle文件中添加以下依赖项

导航到Gradle脚本> build.gradle(Module:app)并将以下依赖项添加到“依赖项”部分。

添加此依赖项后,同步您的项目,现在移至AndroidManifest.xml部分。

步骤3:在AndroidManifest.xml文件中向Internet添加权限

导航至应用程序> AndroidManifest.xml,然后将以下代码添加到其中。

XML


XML


  
    
    
  
    
    
  
    
    


Java
public class DataModal {
      
    // string variables for our name and job
    private String name;
    private String job;
  
    public DataModal(String name, String job) {
        this.name = name;
        this.job = job;
    }
  
    public String getName() {
        return name;
    }
  
    public void setName(String name) {
        this.name = name;
    }
  
    public String getJob() {
        return job;
    }
  
    public void setJob(String job) {
        this.job = job;
    }
      
}


Java
import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.POST;
  
public interface RetrofitAPI {
      
    // as we are making a post request to post a data
    // so we are annotating it with post
    // and along with that we are passing a parameter as users
    @POST("users")
      
    //on below line we are creating a method to post our data.
    Call createPost(@Body DataModal dataModal);
}


Java
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
  
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 {
  
    // creating variables for our edittext, 
    // button, textview and progressbar.
    private EditText nameEdt, jobEdt;
    private Button postDataBtn;
    private TextView responseTV;
    private ProgressBar loadingPB;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // initializing our views
        nameEdt = findViewById(R.id.idEdtName);
        jobEdt = findViewById(R.id.idEdtJob);
        postDataBtn = findViewById(R.id.idBtnPost);
        responseTV = findViewById(R.id.idTVResponse);
        loadingPB = findViewById(R.id.idLoadingPB);
          
        // adding on click listener to our button.
        postDataBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // validating if the text field is empty or not.
                if (nameEdt.getText().toString().isEmpty() && jobEdt.getText().toString().isEmpty()) {
                    Toast.makeText(MainActivity.this, "Please enter both the values", Toast.LENGTH_SHORT).show();
                    return;
                }
                // calling a method to post the data and passing our name and job.
                postData(nameEdt.getText().toString(), jobEdt.getText().toString());
            }
        });
    }
  
    private void postData(String name, String job) {
          
        // below line is for displaying our progress bar.
        loadingPB.setVisibility(View.VISIBLE);
          
        // on below line we are creating a retrofit 
        // builder and passing our base url
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://reqres.in/api/")
                // as we are sending data in json format so 
                // we have to add Gson converter factory
                .addConverterFactory(GsonConverterFactory.create())
                // at last we are building our retrofit builder.
                .build();
        // below line is to create an instance for our retrofit api class.
        RetrofitAPI retrofitAPI = retrofit.create(RetrofitAPI.class);
          
        // passing data from our text fields to our modal class.
        DataModal modal = new DataModal(name, job);
          
        // calling a method to create a post and passing our modal class.
        Call call = retrofitAPI.createPost(modal);
          
        // on below line we are executing our method.
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                // this method is called when we get response from our api.
                Toast.makeText(MainActivity.this, "Data added to API", Toast.LENGTH_SHORT).show();
                  
                // below line is for hiding our progress bar.
                loadingPB.setVisibility(View.GONE);
                  
                // on below line we are setting empty text
                // to our both edit text.
                jobEdt.setText("");
                nameEdt.setText("");
                  
                // we are getting response from our body 
                // and passing it to our modal class.
                DataModal responseFromAPI = response.body();
                  
                // on below line we are getting our data from modal class and adding it to our string.
                String responseString = "Response Code : " + response.code() + "\nName : " + responseFromAPI.getName() + "\n" + "Job : " + responseFromAPI.getJob();
                 
                // below line we are setting our 
                // string to our text view.
                responseTV.setText(responseString);
            }
  
            @Override
            public void onFailure(Call call, Throwable t) {
                // setting text to our text view when 
                // we get error response from API.
                responseTV.setText("Error found is : " + t.getMessage());
            }
        });
    }
}


步骤4:使用activity_main.xml文件

导航到应用程序> res>布局> activity_main.xml,然后将以下代码添加到该文件中。以下是activity_main.xml文件的代码。

XML格式



  
    
    
  
    
    
  
    
    

第5步:创建用于存储数据的模式类

导航到应用程序> Java >应用程序的程序包名称>右键单击它>新建> Java类,并将其命名为DataModal,然后将以下代码添加到其中。在代码内部添加了注释,以更详细地了解代码。

Java

public class DataModal {
      
    // string variables for our name and job
    private String name;
    private String job;
  
    public DataModal(String name, String job) {
        this.name = name;
        this.job = job;
    }
  
    public String getName() {
        return name;
    }
  
    public void setName(String name) {
        this.name = name;
    }
  
    public String getJob() {
        return job;
    }
  
    public void setJob(String job) {
        this.job = job;
    }
      
}

第6步:为我们的API调用创建一个接口类

导航到应用程序> Java >应用程序的程序包名称>右键单击它>新建> Java类,将其选择为Interface并将文件命名为RetrofitAPI并向其添加以下代码。在代码内部添加了注释,以更详细地了解代码。

Java

import retrofit2.Call;
import retrofit2.http.Body;
import retrofit2.http.POST;
  
public interface RetrofitAPI {
      
    // as we are making a post request to post a data
    // so we are annotating it with post
    // and along with that we are passing a parameter as users
    @POST("users")
      
    //on below line we are creating a method to post our data.
    Call createPost(@Body DataModal dataModal);
}

步骤7:使用MainActivity。 Java文件

转到MainActivity。 Java文件并参考以下代码。下面是MainActivity的代码。 Java文件。在代码内部添加了注释,以更详细地了解代码。

Java

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
  
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 {
  
    // creating variables for our edittext, 
    // button, textview and progressbar.
    private EditText nameEdt, jobEdt;
    private Button postDataBtn;
    private TextView responseTV;
    private ProgressBar loadingPB;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // initializing our views
        nameEdt = findViewById(R.id.idEdtName);
        jobEdt = findViewById(R.id.idEdtJob);
        postDataBtn = findViewById(R.id.idBtnPost);
        responseTV = findViewById(R.id.idTVResponse);
        loadingPB = findViewById(R.id.idLoadingPB);
          
        // adding on click listener to our button.
        postDataBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // validating if the text field is empty or not.
                if (nameEdt.getText().toString().isEmpty() && jobEdt.getText().toString().isEmpty()) {
                    Toast.makeText(MainActivity.this, "Please enter both the values", Toast.LENGTH_SHORT).show();
                    return;
                }
                // calling a method to post the data and passing our name and job.
                postData(nameEdt.getText().toString(), jobEdt.getText().toString());
            }
        });
    }
  
    private void postData(String name, String job) {
          
        // below line is for displaying our progress bar.
        loadingPB.setVisibility(View.VISIBLE);
          
        // on below line we are creating a retrofit 
        // builder and passing our base url
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("https://reqres.in/api/")
                // as we are sending data in json format so 
                // we have to add Gson converter factory
                .addConverterFactory(GsonConverterFactory.create())
                // at last we are building our retrofit builder.
                .build();
        // below line is to create an instance for our retrofit api class.
        RetrofitAPI retrofitAPI = retrofit.create(RetrofitAPI.class);
          
        // passing data from our text fields to our modal class.
        DataModal modal = new DataModal(name, job);
          
        // calling a method to create a post and passing our modal class.
        Call call = retrofitAPI.createPost(modal);
          
        // on below line we are executing our method.
        call.enqueue(new Callback() {
            @Override
            public void onResponse(Call call, Response response) {
                // this method is called when we get response from our api.
                Toast.makeText(MainActivity.this, "Data added to API", Toast.LENGTH_SHORT).show();
                  
                // below line is for hiding our progress bar.
                loadingPB.setVisibility(View.GONE);
                  
                // on below line we are setting empty text
                // to our both edit text.
                jobEdt.setText("");
                nameEdt.setText("");
                  
                // we are getting response from our body 
                // and passing it to our modal class.
                DataModal responseFromAPI = response.body();
                  
                // on below line we are getting our data from modal class and adding it to our string.
                String responseString = "Response Code : " + response.code() + "\nName : " + responseFromAPI.getName() + "\n" + "Job : " + responseFromAPI.getJob();
                 
                // below line we are setting our 
                // string to our text view.
                responseTV.setText(responseString);
            }
  
            @Override
            public void onFailure(Call call, Throwable t) {
                // setting text to our text view when 
                // we get error response from API.
                responseTV.setText("Error found is : " + t.getMessage());
            }
        });
    }
}

现在运行您的应用程序,并查看该应用程序的输出。

输出:

想要一个节奏更快,更具竞争性的环境来学习Android的基础知识吗?
单击此处,前往由我们的专家精心策划的指南,以使您立即做好行业准备!