Retrofit2(Android) - 如何沿POST方法发送表单数据

问题描述 投票:0回答:2

* P.s:更改了安全事项的参考资料。

我试图从服务器获取json,但它需要请求体中的表单数据,如下所示:enter image description here

它在postman中测试时有效,但我无法弄清楚如何使用retrofit2来做到这一点。

豆子:

public class Y {

@SerializedName("id")
private int yId;
@SerializedName("name")
private String yName;


//...
}


public class YList {

@SerializedName("ys")
private List<Y> ys;

//...
}

服务接口是这样的:

public interface YService {
@POST("y")
Call<YList> getY()

public static final YService serviceY = new Retrofit.Builder()
        .baseUrl("http://example.com.br/api/x/")
        .addConverterFactory(GsonConverterFactory.create())
        .build()
        .create(YService.class);
}

和REST方法:

YService yService = YService.serviceY;




    yService.getY().enqueue(new Callback<YList>() {
        @Override
        public void onResponse(Call<YList> call, Response<YList> response) {

            if (response.isSuccessful()) {
                //...
            } else {

                //...

            }

        }

        @Override
        public void onFailure(Call<YList> call, Throwable t) {

            //...

        }
    });'

邮差JSON结果:

{
"auth": {
  "validation": true
},
"ys": [
{
  "id": 1,
  "name": "#"
}
]
}
android request http-post retrofit retrofit2
2个回答
1
投票

我设法找到了一个解决方案,结果比我想象的容易得多。

只需创建一个名为AuthRequest的类,如下所示:

public class AuthRequest {

    private static final String TAG = "Auth";
    private static final String EMAIL = "email";
    private static final String PASSWORD = "pass";


    //creates a json-format string
    public static String createAuthJsonString(){

        String info = "{\"auth\":{\"email\":\""+EMAIL+"\",\"password\":\""+PASSWORD+"\"}}";


        Log.i(TAG,info);

        return info;
    }

}

只需将@FormUrlEncoded添加到@Post并将@Field键和值放在方法调用中:

@FormUrlEncoded
@POST("ys")//endpoint
Call<YList> getY(@Field("info") String info);


// Connection url.
public static final YService serviceY = new Retrofit.Builder()
        .baseUrl("http://example.com.br/api/x/")
        .addConverterFactory(GsonConverterFactory.create())
        .build()
        .create(YService.class);

使用getY()方法:

    final YService yService = YService.serviceY;
    //...
    yService.getY(AuthRequest.createAuthJsonString()).enqueue(new 
        Callback<YList>() {

        @Override
        public void onResponse(Call<YList> call, Response<YList> response) {

            if (response.isSuccessful()) {
              //...

            } else {

               //...
            }
        }

        @Override
        public void onFailure(Call<YList> call, Throwable t) {

            //...

        }


    });



}

完美地从json返回YList。


1
投票

Retrofit2 Body with from-data

@FormUrlEncoded 
@POST("xxx")//endpoint
Call<xxxx> getxxx(@Field("phone") String phone);
© www.soinside.com 2019 - 2024. All rights reserved.