我如何在Android中发布JSON数据 [英] How can i POST json data in Android

查看:138
本文介绍了我如何在Android中发布JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我需要 POST 一些数据,这些数据将使用户和 POST 到达服务器.对于服务器请求,我使用 Retrofit2 .
对于 POST ,我应该使用 json 格式进行发布,例如:

In my application I want POST some data, and this data get users and POST to server. For server requests I use Retrofit2.
For POST this data I should POST with json format, such as this :

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

POST 数据之后,我应该使用此结果进行检查,以确保提交的数据没有问题.

After POST data I should check with this results for submit data has Ok ro Not.

{
  "status": 200,
  "Message": "",
  "data": true
}

我从用户处使用EditText提供电子邮件,用户名和密码,但是如何将该数据 POST Json 格式发布到服务器?

I give Email, Username and Password with EditText from users, but how can I POST this data to server with Json format?

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

Please help me, I am amateur and I really need this help

推荐答案

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

Firstly, create a class for your request, for example, LoginRequest.java

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

//getters and setters
}

第二,为您的响应创建一个类LoginResponse.java

Secondly, create a class for your response, LoginResponse.java

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

//getters and setters
}

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

Finally, in your interface add this method:

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

我希望它能为您提供帮助,请问我是否还有其他问题.

I hope It could help you, just ask me if you have more question.

您已经意识到登录方法的返回是一个Call,它是用于异步调用的,您可以在活动中像这样使用它:

have you realised that the return of the login method is a Call, it is for a async call, you could use it like this on your activity:

首先,创建一个改造实例

firstly, create a retrofit instance

Retrofit retrofit = ....

第二,像这样创建您的接口实例:

Secondly, create your interface instance like this:

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

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

Finally, you could access the login method:

    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:

To Convert Objects to Json automatically, you should add a Converter Factory on your retrofit builder:

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

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

别忘了在gradle中导入Gson库.

dont forget import the Gson library on your gradle.

这篇关于我如何在Android中发布JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆