2
私は簡単なアンドロイドアプリケーションを開発しています。しかし、サーバーからの要求本体として必要な両方のキーにヌル値を送信します。私は私のアプリの終わりからそれをチェックしましたが、それはヌル値を送信していません。okhttp投稿のリクエストサーバーにnull値を送信する
ここに私のPHPコードです。
<?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));
?>
ここに私のアンドロイドアプリケーションのコードがあります。
@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());
}
}
}
私はokhttpバージョンv3.5.0を使用しています。私は間違って何をしていますか?
は、REST APIとやり取りするときに 'Retrofit' /' gson'を使用することをおすすめします。 –
これを参照してくださいhttp://stackoverflow.com/questions/32856401/using-okhttp-library-for-posting-to-a-php-script-that-saves-to-mysqlそれは完全な例を持っています.. – rafsanahmad007
@ rafsanahmad007それはokhttpの古いバージョンです。私が探している答えではありません。私のコードのエラーを指摘しておきます。 –