【问题标题】:Retrofit URL with query param使用查询参数改造 URL
【发布时间】:2018-02-11 12:32:58
【问题描述】:

我第一次尝试使用改造,但缺少简单的逻辑。请帮我解决这个问题。

这是我的用户类

public class User {

    private String name, email, password;

    public User(){
    }

    public User(String name, String email, String password){
        this.name = name;
        this.email = email;
        this.password = password;
    }

    public String getName() {
        return name;
    }

    public String getEmail() {
        return email;
    }

    public String getPassword() {
        return password;
    }


    public void setName(String name) {
        this.name = name;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

API 接口

   public interface MyApiEndpointInterface {
        // Request method and URL specified in the annotation
        // Callback for the parsed response is the last parameter

        @GET("users?email={email}")
        Call<User> getUser(@Query("email") String email);
     }

这是我获取详细信息的方式:

 public void getUserDetails()
{
    String email = inputEmail.getText().toString()
    Call<User> call = apiService.getUser(email);

    call.enqueue(new Callback<User>() {
        @Override
        public void onResponse(Call<User>call, Response<User> response) {
            if(response.body()!=null)
            {
                Log.d("TAG", "Name: " + response.body().getName());
                Log.d("TAG", "Password: " + response.body().getPassword());
            }
            else
            {
                Toast.makeText(getApplicationContext(), "User does not exist", Toast.LENGTH_SHORT).show();
                Log.d("TAG", "User details does not exist");
            }
        }

        @Override
        public void onFailure(Call<User>call, Throwable t) {
            Log.e("TAG", t.toString());
        }
    });
}

现在我的问题是我有托管在服务器上的 web api,它看起来像:

http://www.somesite.com

要根据提供的电子邮件获取用户详细信息,我正在尝试使用此功能:

http://www.somesite.com/api/user?email={email}

现在如何在 api 接口中将这个 url 设置为返回 null ?

【问题讨论】:

    标签: java android json retrofit2


    【解决方案1】:

    在您的 apiService 中,您应该使用 Builder 创建一个 Retrofit 对象,并以此创建您的 MyApiEndpointInterface 接口的实例。在此处添加 API 的 baseUrl。

    它应该看起来像这样:

    Retrofit retrofit = new Retrofit.Builder()
                    .baseUrl("http://yourapibaseUrl.com/api/")
                    .build();
    
    MyApiEndpointInterface apiInterface = retrofit.create(MyApiEndpointInterface.class);
    

    apiInterface 是您将用于使用 Refit 调用 API 的对象,它已经设置了 baseUrl。

    希望这会有所帮助。-

    【讨论】:

    • 啊傻...刚才我也看到它不见了...谢谢哥们:)
    猜你喜欢
    • 2016-08-12
    • 2019-05-15
    • 1970-01-01
    • 2015-05-14
    • 2020-08-07
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    相关资源
    最近更新 更多