如何使用HttpPost类将数据从android发送到mysql?

问题描述 投票:0回答:1

我想用android做一个简单的游戏。我已经做了一个注册页面。我想将用户名和密码传输到mysql服务器。我尝试通过使用HttpPost类将发布请求发送到http://peeyshapps.epizy.com/add_entry.php来完成此操作,但是它不起作用,我的数据库中没有任何条目。我该如何解决?预先感谢。

add_entry.php包含:


<?php
    $response=array();
    $User=$_REQUEST["User"];
    $pass=$_REQUEST["Pass"];
    $conn=mysqli_connect("sql304.epizy.com","my_username","my_password","epiz_25639733_PWord") or die("SERVER ERROR!<br>ERR_Connection");
    $result=mysqli_query($conn,"INSERT INTO `Users`(`User`, `Password`) VALUES (\"$User\",\"$pass\")");
    if($result)
        $response[status]=1;
    else
        $response[status]=0;
    echo json_encode($response);
 ?>

用于注册的xml文件页面包含:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/blk"
        android:text="Sign Up"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textColor="@color/whte"
        android:textSize="35sp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/textView2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Username:"
            android:textAppearance="?android:attr/textAppearanceMedium" />

    </LinearLayout>

    <EditText
        android:id="@+id/User"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPersonName" >

        <requestFocus />
    </EditText>

    <TextView
        android:id="@+id/textView3"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Password"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/pass1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPassword" />

    <TextView
        android:id="@+id/textView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Confirm Password"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <EditText
        android:id="@+id/pass2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:inputType="textPassword" />

    <Button
        android:id="@+id/signup_main"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#00f"
        android:text="SignUp"
        android:textColor="#fff"
        android:textSize="25sp"
        android:onClick="addEntry" />

</LinearLayout>

MainActivity.java包含:

package com.peeyush.pword;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

    EditText user,pass1,pass2;
    InputStream is=null;
    String line=null;
    String result=null;
    int code;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        if(!Initialiser.initial())
            setContentView(R.layout.sig_or_log);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.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();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    public void go_Sign(View v) {
        setContentView(R.layout.signup);
    }

    public void addEntry(View v)
    {
        user=(EditText) findViewById(R.id.User);
        pass1=(EditText)findViewById(R.id.pass1);
        pass2=(EditText)findViewById(R.id.pass2);
        String usr=user.getText().toString(),p1=pass1.getText().toString(),p2=pass2.getText().toString();
        if(usr.trim().equals("") || p1.trim().equals(""))
            Toast.makeText(this, "Username or password can't be empty", Toast.LENGTH_LONG).show();
        if(!p1.equals(p2))
            Toast.makeText(this, "Password didn't match", Toast.LENGTH_LONG).show();
        else
        {
            InsertData(usr,p1);
        }
    }
    public void InsertData(final String name, final String email){

        class SendPostReqAsyncTask extends AsyncTask<String, Void, String> {
            @Override
            protected String doInBackground(String... params) {

                String NameHolder = name ;
                String EmailHolder = email ;

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

                nameValuePairs.add(new BasicNameValuePair("User", NameHolder));
                nameValuePairs.add(new BasicNameValuePair("Pass", EmailHolder));

                HttpClient httpClient = new DefaultHttpClient();

                HttpPost httpPost = new HttpPost("http://peeyshapps.epizy.com/add_entry.php");

                httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

                HttpResponse httpResponse = httpClient.execute(httpPost);

                HttpEntity httpEntity = httpResponse.getEntity();

                return "Data Inserted Successfully";
            }

            @Override
            protected void onPostExecute(String result) {

                super.onPostExecute(result);

                Toast.makeText(MainActivity.this, "Data Submit Successfully", Toast.LENGTH_LONG).show();

            }
        }

        SendPostReqAsyncTask sendPostReqAsyncTask = new SendPostReqAsyncTask();

        sendPostReqAsyncTask.execute(name, email);
    }
}
java php android mysql httpclient
1个回答
0
投票

尝试更改PHP以显示一些错误并检查是否返回任何内容:

$response=array();
$User=$_REQUEST["User"];
$pass=$_REQUEST["Pass"];
$conn=mysqli_connect("sql304.epizy.com","my_username","my_password","epiz_25639733_PWord") or die("SERVER ERROR!<br>ERR_Connection");

if(!$conn){
    $response["mysqliError"] = mysqli_connect_errno() . ": " . mysqli_connect_error();
}

$result=mysqli_query($conn,"INSERT INTO `Users`(`User`, `Password`) VALUES (\"$User\",\"$pass\")");
if($result)
    $response["status"]=1;
else
    $response["mysqliError"] = mysqli_errno($conn) . ": " . mysqli_error($conn);
    $response["status"]=0;
echo json_encode($response);

我这里没有PHP IDE,因此无法测试代码。可能会错过某些语法或类似内容

© www.soinside.com 2019 - 2024. All rights reserved.