简体   繁体   中英

How can i POST json data in Android

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",
}

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

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

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

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
}

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.

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(...){
}
    }

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))
...

dont forget import the Gson library on your gradle.

Here is a tutorial on Retrofit 2: http://www.vogella.com/tutorials/Retrofit/article.html

Alternatively, you can use Volley, it is a library specificaly designed to make http requests on Android. https://developer.android.com/training/volley/index.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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