gpt4 book ai didi

android - 使用 Retrofit 发送 POST 参数

转载 作者:太空狗 更新时间:2023-10-29 15:35:45 24 4
gpt4 key购买 nike

我正在尝试通过 Retrofit 实现 POST 请求,但我猜这种方法似乎是错误的。我遵循了用于 GET 请求的步骤:

我定义了终点:

 public interface GitHubEmailAPI {

@POST("/users/{user}")
Call<GitHubEmail> postEmail(@Field("email") String email);
}

模型:

    public class GitHubEmail {

@SerializedName("email")
private String email;

public String getEmail() {
return email;
}

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

还有呼唤:

 public void postEmail (){
GitHubEmailAPI apiService =
ApiClient.getClient().create(GitHubEmailAPI.class);

final Call<GitHubEmail> callEmail = apiService.postEmail
(String.valueOf(enterEmailEt.getText()));

callEmail.enqueue(new Callback<GitHubEmail>() {
@Override
public void onResponse(Call<GitHubEmail> call, Response<GitHubEmail> response) {
testTV.setText(callEmail.toString());
}

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

}
});

我正在使用 github api 作为测试,不确定是否需要将访问 token 作为参数包含在请求中。

最佳答案

关于Retrofit,你知道一些信息......

  1. Your BASE_URL must be end with / .

  2. When you using @Field notation you must put @FormUrlEncoded in Your Api call.

  3. When you using {user} in the API method you have to use @Path("user") String user to relate to url data .

  4. Your POST method URL will be like this @POST("users/{user}").

  5. When your response Callback done the actual Data inside your Response<GitHubEmail> response in this variable. You have to use response.body() to get what you get response from API CALL.

这是一个示例代码

@FormUrlEncoded
@POST("users/{user}")
Call<YourResultPojoClassHere> yourFuntionName(@Field("id") String id,@Path("user") String path);

请看下面的代码....

callEmail.enqueue(new Callback<GitHubEmail>() {
@Override
public void onResponse(Call<GitHubEmail> call, Response<GitHubEmail> response) {
if (response.isSuccessful()) {
if (response.body().getSuccess())

Toast.makeText(ClassName.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
else
Toast.makeText(ClassName.this, response.body().getMessage(), Toast.LENGTH_SHORT).show();
} else
Toast.makeText(ClassName.this, "Sorry for inconvince server is down", Toast.LENGTH_SHORT).show();

}

@Override
public void onFailure(Call<GitHubEmail> call, Throwable t) {
Toast.makeText(ClassName.this, "Check your Internet connection", Toast.LENGTH_SHORT).show();
}
}
});

关于android - 使用 Retrofit 发送 POST 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39673639/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com