使用OkHttp库发布到保存到MySQL的PHP​​脚本 [英] Using OkHttp library for posting to a PHP script that saves to MySQL

查看:62
本文介绍了使用OkHttp库发布到保存到MySQL的PHP​​脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写将新用户注册到服务器的代码.为了做到这一点,我使用OkHttp库实现了POST请求.

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

当我输入用户信息(电子邮件,姓名,密码,生日)并在活动上按注册按钮时,它应将请求正文发送到服务器(使用PHP开发)应接收并存储用户数据到MySQL数据库中,但一直失败.我应该如何修改代码,以便用户数据成功存储在MySQL数据库中?

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?

(已编辑)

下面的代码是PHP部分.

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.

推荐答案

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

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;

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

`

这是main_activity.xml

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>

` 类测试{
函数test_me(){
$ username = $ _POST ['username'];
//回显$ _POST;
var_dump($ _ POST);
}
}

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

//调用类
$ test = new Test();
$ test-> test_me();

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

?> `

这篇关于使用OkHttp库发布到保存到MySQL的PHP​​脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆