如何在Android中发布json数据

时间:2017-05-04 15:18:26

标签: android json retrofit2

在我的应用程序中,我想要 POST 一些数据,这些数据会让用户和 POST 到服务器。对于服务器请求,我使用 localhost 对于 POST 此数据,我应该使用 Retrofit2 格式进行发布,例如:

json

发布数据后,我应该检查此结果,以便提交数据有Ok ro Not。

{
  "email": "example@example.com",
  "username": "example",
  "password": "123",
}

我使用{ "status": 200, "Message": "", "data": true } 向用户提供电子邮件,用户名和密码,但如何 {<1}} 格式 POST 此数据到服务器?

请帮助我,我是业余爱好者,我真的需要这个帮助

2 个答案:

答案 0 :(得分:2)

首先,为您的请求创建一个类,例如LoginRequest.java

public class LoginRequest {
private String email;
private String username;
private String password;

//getters and setters
}

其次,为您的响应创建一个类,LoginResponse.java

public class LoginResponse {
private Integer status;
private String Message;
private Boolean data;

//getters and setters
}

最后,在您的界面中添加此方法:

public interface MiApiInterface {
    @POST("yourResourceName") Call<LoginResponse> login(@Body LoginRequest request);
}

我希望它可以帮助你,只要问你是否有更多问题。

你是否意识到登录方法的返回是一个Call,它是一个异步调用,你可以在你的活动中使用它:

首先,创建一个改造实例

Retrofit retrofit = ....

其次,像这样创建你的接口实例:

MiApiInterface apiInterface = retrofit.create(MiApiInterface.class);

最后,您可以访问登录方法:

    LoginRequest request = new LoginRequest();
    request.set();
    ....

    Call<LoginResponse> responseCall = apiInterface.login(request);

    responseCall.enqueue(new Callback<LoginResponse>() {
public void onResponse(...){
LoginResponse loginResponse = response.body();
}

public void onFailure(...){
}
    }

要自动将对象转换为Json,您应该在改装构建器上添加Converter Factory:

Gson gson = new GsonBuilder().create();

Retrofit.Builder()
                .baseUrl(baseUrl)
                .addConverterFactory(GsonConverterFactory.create(gson))
...

不要忘记在你的gradle上导入Gson库。

答案 1 :(得分:0)

以下是有关Retrofit 2的教程:http://www.vogella.com/tutorials/Retrofit/article.html

或者,您可以使用Volley,它是专门为在Android上发出http请求而设计的库。 https://developer.android.com/training/volley/index.html

相关问题