首页 > 解决方案 > 如何在 Retrofit 中将变量传递给 GET 参数

问题描述

我是java和Android的新手。我正在尝试将一些变量传递给 Retrofit GET-Call。但是对我没有任何作用,所以请您看一下我的代码吗?

我必须更改什么才能发送我的变量:

到服务器?

我的java文件:


    public class Orte extends AppCompatActivity {

...

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_orte);

        Intent myIntent = getIntent(); // gets the previously created intent
        myActuelFullName = myIntent.getStringExtra("paramFullName"); // will return "paramFullName"

        getEntries(myActuelFullName);
    }


    private void getEntries(String myActuelFullName) {

                Retrofit retrofit = new Retrofit.Builder()
                .baseUrl("http://myDomain.de/api/")
                .addConverterFactory(GsonConverterFactory.create())
                .build();

        JsonPlaceHolderApi jsonPlaceHolderApi = retrofit.create(JsonPlaceHolderApi.class);

        String myOtherInfo = "testing123";

        Call<List<Entries>> call = jsonPlaceHolderApi.getEntries();
        Log.d("DEBUG", myActuelFullName ); // at this point the Variable is known!

        call.enqueue(new Callback<List<Entries>>() {
            @Override
            public void onResponse(Call<List<Entries>> call, Response<List<Entries>> response) {
                if (!response.isSuccessful()) {
                    //textViewResult.setText("Code: " + response.code());
                    return;
                }
//


            @Override
            public void onFailure(Call<List<Entries>> call, Throwable t) {
                //  textViewResult.setText(t.getMessage());
            }
        });

还有我的占位符 Api:

public interface JsonPlaceHolderApi {


    @GET("get_entries.php")
    Call<List<Entries>> getEntries();

    @POST("http://myDomain.de/api/mypost.php/")
    Call<Post> createPost(@Body Post post);

}

标签: javaandroidretrofitparameter-passingretrofit2

解决方案


您必须首先在 API 接口类中添加查询参数。添加两个查询参数后,您的类应如下所示:

public interface JsonPlaceHolderApi {


    @GET("get_entries.php")
    Call<List<Entries>> getEntries(@Query("myActuelFullName") String myActuelFullName, @Query("myOtherInfo") String myOtherInfo);

    @POST("http://myDomain.de/api/mypost.php/")
    Call<Post> createPost(@Body Post post);

}

在您的活动中,函数调用应如下所示:

Call<List<Entries>> call = jsonPlaceHolderApi.getEntries(myActuelFullName,myOtherInfo);

推荐阅读