简体   繁体   English

使用正文参数 android 改造 POST 请求

[英]Retrofit POST Request with body parameters android

I need to execute post request with retrofit but i have a problem which i can't understand very well.我需要通过改造来执行发布请求,但我有一个我不能很好理解的问题。 Before trying with code i tested api call with Postman and request look like this:在尝试使用代码之前,我使用Postman测试了 api 调用,请求如下所示:

捕获1 在此处输入图像描述

Here is my android code:这是我的安卓代码:

public class API {

private static <T> T builder(Class<T> endpoint) {

    return new Retrofit.Builder()
            .baseUrl(Utils.API_BASE_URL)
            .addConverterFactory(ScalarsConverterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .build()
            .create(endpoint);
}
public static AllRequests request() {
    return builder(AllRequests.class);
}
}

EDIT request:编辑请求:

@POST("api/android-feedback")
@Headers({"Content-Type: application/x-www-form-urlencoded", "Authorization: F#@3FA@#Rad!@%!2s"})
Call<String> sendFeedback(@Body FeedbackBody body);

FeedbackBody:反馈机构:

public class FeedbackBody{
private final String email;
private final String feedback;

public FeedbackBody(String email, String feedback){
    this.email = email;
    this.feedback = feedback;
}

} }

And finally i construct the request and wait for response, the problem is that i receive message in onFail method最后我构造请求并等待响应,问题是我在 onFail 方法中收到消息

   private void sendFeedbackRequest(){
    API.request().sendFeedback(new FeedbackBody("testmeil@meil.com", "test feedback").enqueue(new Callback<String>() {
        @Override
        public void onResponse(Call<String> call, Response<String> response) {
            goToMainActivity();
        }

        @Override
        public void onFailure(Call<String> call, Throwable t) {
            Toast.makeText(SplashScreenActivity.this, R.string.try_again_later, Toast.LENGTH_SHORT).show();
        }
    });

EDIT: Still not working.. i think i figure it out where can be the problem, because server side wait for simple POST request without Json formatting, i think Retrofit use JSON formatting by default, and if i send POST request and format Body parameters with JSON the server will fail to parse my request, is there any chance to send simple POST request like at POSTMAN without formatting with JSON ?编辑:仍然无法正常工作..我想我知道问题出在哪里,因为服务器端等待没有 Json 格式的简单 POST 请求,我认为 Retrofit 默认使用 JSON 格式,如果我发送 POST 请求并格式化 Body 参数使用 JSON,服务器将无法解析我的请求,是否有机会像在 POSTMAN 一样发送简单的 POST 请求而不使用 JSON 格式化?

  • Php api wait request to be send like this: php api 等待请求发送如下:

$_POST['feedback'] = 'blabla'; $_POST['feedback'] = 'blabla'; $_POST['email'] = 'blabla..'; $_POST['email'] = 'blabla..';

and if he receive Json format request can't parse it and because of that i receive fail response.如果他收到 Json 格式请求无法解析它,因此我收到失败响应。

First you need to create request( POJO Class)首先你需要创建请求(POJO 类)

public class FeedbackRequest {
   public String email;
   public String feedback;
}

when you call sendFeedbackRequest() pass the FeedbackRequest like below"当您调用sendFeedbackRequest()时,传递如下的FeedbackRequest "

FeedbackRequest req = new FeedbackRequest();
req.email= "email";
req.feedback= "feedback"
sendFeedbackRequest(req)

after that your sendFeedbackRequest() should be like this之后你的sendFeedbackRequest()应该是这样的

  private void sendFeedbackRequest(FeedbackRequest request){
      API.request().sendFeedback(request).enqueue(new Callback<String>() {
      @Override
      public void onResponse(Call<String> call, Response<String> response) {
        goToMainActivity();
      }

      @Override
      public void onFailure(Call<String> call, Throwable t) {
        Toast.makeText(SplashScreenActivity.this, R.string.try_again_later, Toast.LENGTH_SHORT).show();
    }
});

And your retrofit request should be like this,而你的改造要求应该是这样的,

@FormUrlEncoded
@POST("api/android-feedback")
@Headers({"Content-Type: application/json", "Authorization: F31daaw313415"})
Call<String> sendFeedback(@Body FeedbackRequest request);

Now it should work.现在它应该可以工作了。 feel free to ask anything.随便问什么。

You are using a Gson converter factory.您正在使用 Gson 转换器工厂。 It might be easier to create a single object that represents your body, and use that instead of all individual parameters.创建一个代表您的身体的对象可能更容易,并使用它而不是所有单独的参数。 That way, you should be able to simple follow along with the examples on the Retrofit website.这样,您应该能够简单地按照 Retrofit 网站上的示例进行操作。 enter link description here There are also many site that let you generate your Plain Old Java Objects for you, like this one :在此处输入链接描述还有许多站点可以让您为您生成普通旧 Java 对象,例如:

Eg your Api call:例如你的 Api 调用:

@POST("api/android-feedback")
Call<String> sendFeedback(@Body FeedbackBody feedback);    

And your FeedbackBody class:还有你的 FeedbackBody 类:

public class FeedbackBody{
    private final String email;
    private final String feedback;

    public FeedbackBody(String email, String feedback){
        this.email = email;
        this.feedback = feedback;
    }
}

Java:爪哇:

@POST("/api/android-feedback")
Call<String> sendFeedback(@Body FeedbackBody feedback);

Kotlin:科特林:

@POST("/api/android-feedback")
fun sendFeedback(@Body feedback: FeedbackBody): Call<String>

Also, probably you forgot leading slash in the endpoint.此外,您可能忘记了端点中的前导斜杠。

  val formBody: RequestBody = FormBody.Builder()
            .add("username", LoginRequest.username)
            .add("password", LoginRequest.password)
            .add("grant_type",LoginRequest.grant_type)
            .add("client_id", LoginRequest.client_id)
            .add("client_secret", LoginRequest.client_secret)
            .add("cleartext", LoginRequest.cleartext)
            .build()

@POST(EndPoints.GENERATE_TOKEN_URL)
    @Headers("Content-Type: application/x-www-form-urlencoded")
    suspend fun getLogin(
        @Body formBody: RequestBody
    ): LoginResponse

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM