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

时间:2018-01-07 16:10:23

标签: android request http-post retrofit retrofit2

* 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) {

            //...

        }
    });'

Postman JSON结果:

{
"auth": {
  "validation": true
},
"ys": [
{
  "id": 1,
  "name": "#"
}
]
}

2 个答案:

答案 0 :(得分:1)

Retrofit2 Body with from-data

@FormUrlEncoded 
@POST("xxx")//endpoint
Call<xxxx> getxxx(@Field("phone") String phone);

答案 1 :(得分:0)

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

只需创建一个名为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。