I'm developing simple android application that making simple post request to server. But it sending null values for both keys which are required as request body from server. I've check it from my app end but it's not sending null values.
here's my php code.
<?php
include 'DBConnection.php';
$db = DBConnection::getInstance ();
$db = DBConnection::getInstance ();
$mysqli = $db->getConnection ();
$username = $_POST ['username'];
$password = $_POST ['password'];
$result_array = array (
"username " => $username,
"password " => $password
);
echo (json_encode($result_array));
?>
Here's the code in my android application.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new LoginPostRequest().execute(RestConnection.LOGIN_POST);
}
});
}
private class LoginPostRequest extends AsyncTask<String, Object, String> {
private RequestBody body;
@Override
protected void onPreExecute() {
String userNameData = userName.getText().toString().replace(" ","");
String PasswordData = password.getText().toString().replace(" ","");
JSONObject requestBody = new JSONObject();
try {
requestBody.put("username", userNameData);
requestBody.put("password", PasswordData);
} catch (JSONException e) {
Log.d(TAG,"Login onPreExecute"+e.getLocalizedMessage());
}
String string = requestBody.toString();
body = RequestBody.create(JSON, string);
}
@Override
protected String doInBackground(String... params) {
String urlEndPoint = params[0];
Request request = new Request.Builder()
.url(RestConnection.API_BASE+urlEndPoint)
.post(body)
.build();
try {
Response response = client.newCall(request).execute();
return response.body().string();
} catch (IOException e) {
e.printStackTrace();
}
return "String";
}
@Override
protected void onPostExecute(String response) {
JSONObject responseBody;
try {
responseBody = new JSONObject(response);
String message = responseBody.getString("message");
if(!message.equals("login failed")){
Toast.makeText(MainActivity.this,message,Toast.LENGTH_LONG).show();
Intent i = new Intent(MainActivity.this,MainMenuActivity.class);
startActivity(i);
finish();
}else{
Toast.makeText(MainActivity.this,message,Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Log.d(TAG,"Login onPostExecute :"+e.getLocalizedMessage());
}
}
}
I'm using okhttp version v3.5.0. What am I doing wrong?