Using OkHttp library for posting to a PHP script that saves to MySQL

怎甘沉沦 提交于 2019-12-14 03:44:45

问题


I am writing a code that registers a new user to the server. In order to do so, I implemented a POST request using OkHttp library.

public class RegistrationManager {
    private final String TAG_REGISTER = RegistrationManager.class.getSimpleName();
    private OkHttpClient client = new OkHttpClient();
    private final String registrationURL = URL.getInstance().getUrlRegister();

    public void registerUser(final User newUser) {
        RequestBody body = new FormEncodingBuilder()
                .add("email", newUser.getEmail())
                .add("name", newUser.getName())
                .add("password", newUser.getPassword())
                .add("birthday", newUser.getBirthday())
                .build();

        Request request = new Request.Builder().url(registrationURL).post(body).build();

        Call call = client.newCall(request);

        call.enqueue(new Callback() {

            @Override
            public void onFailure(Request request, IOException e) {
                Log.e(TAG_REGISTER, "Registration error: " + e.getMessage());
            }

            @Override
            public void onResponse(Response response) throws IOException {

                try {
                    String resp = response.body().string();
                    Log.v(TAG_REGISTER, resp);
                    if(response.isSuccessful()) {

                    } else {

                    }
                } catch(IOException e) {
                    Log.e(TAG_REGISTER, "Exception caught: ", e);
                }
            }
        });
    }
}

When I enter the user information (email, name, password, birthday) and press register button on the activity, it should send the request body to the server (which is developed in PHP) should receive it and store the user data into the MySQL database, but it keeps failing to do so. How should I modify the code so that the user data is successfully stored in the MySQL database?

(edited)

The code below is the PHP part.

<?php

if (isset($_POST['tag']) && $_POST['tag'] != '') {
    // get tag
    $tag = $_POST['tag'];

    // include db handler
    require_once 'include/DB_Functions.php';
    $db = new DB_Functions();

    // response Array
    $response = array("tag" => $tag, "error" => FALSE);

    // check for tag type
    if ($tag == 'login') {
        // Request type is check Login
        $email = $_POST['email'];
        $password = $_POST['password'];

        // check for user
        $user = $db->getUserByEmailAndPassword($email, $password);
        if ($user != false) {
            // user found
            $response["error"] = FALSE;
            $response["uid"] = $user["unique_id"];
            $response["user"]["name"] = $user["name"];
            $response["user"]["email"] = $user["email"];
            $response["user"]["birthday"] = $user["birthday"];
            $response["user"]["created_at"] = $user["created_at"];
            $response["user"]["updated_at"] = $user["updated_at"];
            echo json_encode($response);
        } else {
            // user not found
            // echo json with error = 1
            $response["error"] = TRUE;
            $response["error_msg"] = "Incorrect email or password!";
            echo json_encode($response);
        }
    } else if ($tag == 'register') {
        // Request type is Register new user
        $name = $_POST['name'];
        $email = $_POST['email'];
        $password = $_POST['password'];
        $birthday = $_POST['birthday'];

        // check if user is already existed
        if ($db->isUserExisted($email)) {
            // user is already existed - error response
            $response["error"] = TRUE;
            $response["error_msg"] = "User already exists";
            echo json_encode($response);
        } else {
            // store user
            $user = $db->storeUser($name, $email, $password, $birthday);
            if ($user) {
                // user stored successfully
                $response["error"] = FALSE;
                $response["uid"] = $user["unique_id"];
                $response["user"]["name"] = $user["name"];
                $response["user"]["email"] = $user["email"];
                $response["user"]["birthday"] = $user["birthday"];
                $response["user"]["created_at"] = $user["created_at"];
                $response["user"]["updated_at"] = $user["updated_at"];
                echo json_encode($response);
            } else {
                // user failed to store
                $response["error"] = TRUE;
                $response["error_msg"] = "Error occured in Registartion";
                echo json_encode($response);
            }
        }
    } else {
        // user failed to store
        $response["error"] = TRUE;
        $response["error_msg"] = "Unknow 'tag' value. It should be either 'login' or 'register'";
        echo json_encode($response);
    }
} else {
    $response["error"] = TRUE;
    $response["error_msg"] = "Required parameter 'tag' is missing!";
    echo json_encode($response);
}
?>

If you need further information, please let me know any time. I am really eager to find out what the problem is, and solve it.


回答1:


Check IP addrress, if you are using a simulator, use this one: Also make sure you are trapping user inputs on button click, like shown here below:

MainActivitiy.java

`package com.example.abdimuna.munokhttp;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.squareup.okhttp.Call;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.FormEncodingBuilder;
import com.squareup.okhttp.OkHttpClient;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.RequestBody;
import com.squareup.okhttp.Response;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    private static final String BASE_URL = "http://10.0.2.2/tcdc/check2.php";
    private OkHttpClient client = new OkHttpClient();
    EditText userNameTextEdit, passwordTextEdit;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //
        userNameTextEdit = (EditText) findViewById(R.id.usernameText);
        passwordTextEdit = (EditText) findViewById(R.id.passwordText);
        Button login = (Button) findViewById(R.id.loginButton);
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // handle login
                String username = userNameTextEdit.getText().toString();
                String password = passwordTextEdit.getText().toString();
                registerUser(username, password);
            }
        });
    }

    public void registerUser(String username, String password) {
        RequestBody body = new FormEncodingBuilder()
                .add("username", username)
                .add("password", password)
                .build();
        Request request = new Request.Builder().url(BASE_URL).post(body).build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {

            @Override
            public void onFailure(Request request, IOException e) {
                //  Log.e(TAG_REGISTER, "Registration error: " + e.getMessage());
                System.out.println("Registration Error" + e.getMessage());
            }

            @Override
            public void onResponse(Response response) throws IOException {
                try {
                    String resp = response.body().string();
//                    Log.v(TAG_REGISTER, resp);
                    System.out.println(resp);
                    if (response.isSuccessful()) {
                    } else {

                    }
                } catch (IOException e) {
                    // Log.e(TAG_REGISTER, "Exception caught: ", e);
                    System.out.println("Exception caught" + e.getMessage());
                }
            }
        });
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

`

Here is main_activity.xml

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Username"
            android:id="@+id/textView"
            android:textColor="#ff7459"
            android:textSize="25dp"
            android:layout_marginTop="42dp"
            android:layout_below="@+id/textview"
            android:layout_centerHorizontal="true" />

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/usernameText"
            android:hint="username"
            android:focusable="true"
            android:textColorHighlight="#ff7eff15"
            android:textColorHint="#ffff25e6"
            android:layout_marginTop="46dp"
            android:singleLine="true"
            android:layout_below="@+id/imageView"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/imageView"
            android:layout_below="@+id/textView"
            android:layout_centerHorizontal="true" />

        <EditText
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:inputType="textPassword"
            android:ems="10"
            android:id="@+id/passwordText"
            android:singleLine="true"
            android:layout_below="@+id/editText"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignRight="@+id/editText"
            android:layout_alignEnd="@+id/editText"
            android:textColorHint="#ffff299f"
            android:hint="Password" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Login"
            android:id="@+id/loginButton"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true"
            android:layout_below="@+id/editText2" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="register"
            android:id="@+id/button2"
            android:layout_alignParentLeft="true"
            android:layout_alignParentStart="true"
            android:layout_below="@+id/button"
            android:layout_alignParentRight="true"
            android:layout_alignParentEnd="true" />
    </TableLayout>
</ScrollView>

` class Test{
function test_me(){
$username = $_POST['username'];
//echo $_POST;
var_dump($_POST);
}
}

// calling the class
$test = new Test();
$test->test_me();

?> `



来源:https://stackoverflow.com/questions/32856401/using-okhttp-library-for-posting-to-a-php-script-that-saves-to-mysql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!