Reputation: 104
I don't understand the difference, I have coded an example where my application sends username and password to the server using a POST request using retrofit2.
I first tried sending the request with @Body tag in the interface method:`
@POST("/testproject/login.php")
Call<TestResponse> sendUsernamePassword(@Body UserData userData);
But my login.php responded with no body tags(username,password) received.
Then I change the method to send request using FormEncoding:
@FormUrlEncoded
@POST("/testproject/login.php")
Call<TestResponse> sendUsernamePassword(@Field("username")String username,
@Field("password")String password);
And it started working, But I don't understand why retrofit couldn't send post request using @Body annotation.
Here is login.php
file
<?php
if (isset($_POST['username']) && isset($_POST['password'])) {
$response['status'] = 'success';
$response['username'] = $_POST['username'] . " received";
$response['password'] = $_POST['password'] . "received";
echo json_encode($response);
} else {
$response['status'] = 'failure';
echo json_encode($response);
}
?>
Can someone explain what's the difference and how can it be fixed?
Upvotes: 2
Views: 1516
Reputation: 644
@Body
– Sends Java objects as request body.
@Field
– Send data as form-urlencoded. The @Field parameter works only with a POST.
In order to read POST json body in php, you can use the following code:
//Get the request body
$inputJSON = file_get_contents('php://input');
//Convert into array
$input = json_decode($inputJSON, TRUE);
$username = $input['username'];
$password = $input['password'];
Upvotes: 7