使用 OkHttp 库发布到保存到 MySQL 的 PHP 脚本

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

我正在编写一个代码来向服务器注册一个新用户。为此,我使用 OkHttp 库实现了一个 POST 请求。

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);
                }
            }
        });
    }
}

当我输入用户信息(电子邮件、姓名、密码、生日)并按下 activity 上的注册按钮时,它应该将请求正文发送到服务器(在 [=26= 中开发) ]) 应该接收它并将用户数据存储到 MySQL 数据库中,但它一直未能这样做。应该如何修改代码才能使用户数据成功存入MySQL数据库?

(已编辑)

下面的代码是PHP部分。

<?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);
}
?>

如果您需要更多信息,请随时告诉我。我真的很想找出问题所在,并解决它。

检查 IP 地址,如果您使用的是模拟器,请使用这个: 还要确保在单击按钮时捕获用户输入,如下所示:

MainActivitiy.java

`包 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);
    }
}

`

这是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_me(){
$用户名 = $_POST['username'];
//回显$_POST;
var_dump($_POST);
}
}

// 调用 class
$test = new Test();
$测试->test_me();

?> `