java - $_POST 未从 Java 代码接收数据

标签 java php android sql

我是一个新手,正在为 Android 创建基本登录应用程序,使用 000webhost 作为我的服务器。

我的Java代码:

ArrayList<NameValuePair> dataToSend = new ArrayList<>();
        dataToSend.add(new BasicNameValuePair("name", user.name));
        dataToSend.add(new BasicNameValuePair("email", user.email));
        dataToSend.add(new BasicNameValuePair("password", user.password));
        dataToSend.add(new BasicNameValuePair("leagueID", user.leagueID + ""));

        HttpParams httpRequestParams = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
        HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);

        HttpClient client = new DefaultHttpClient(httpRequestParams);
        HttpPost post = new HttpPost("http://subdomain.site88.net/register.php");

        try{
            post.setEntity(new UrlEncodedFormEntity(dataToSend));
            client.execute(post);
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;

我的 PHP 代码

<?php
$con = mysqli_connect("mysql1.000webhost.com", "username", "password", "dbname");

/***I want to get this data from Java side of application***/
$name = $_POST["name"];
$email = $_POST["email"];
$password = $_POST["password"];
$leagueID = $_POST["LeagueID"];

/***this works
$name = "John Doe";
$email = "JohnDoe@gmail.com";
$password = "password"
$leagueID = 0;
***/

echo "Hello";//place this here to check website to see if its showing up

//Now we will add the name, email, password, and leagueID into a table called "user".
$statement = mysqli_prepare($con, "INSERT INTO user (email, name, password, leagueID) VALUES (?, ?, ?, ?)"); 
mysqli_stmt_bind_param($statement, "sssi", $email, $name, $password, $leagueID);
mysqli_stmt_execute($statement);
mysqli_stmt_close($statement);
//finish up by closing the connection
mysqli_close($con);
?>

如果我将这些值硬连接到 PHP 代码中而不是使用 $_POST 方法,则会按请求将其发送到数据库。但是,$_POST 变量似乎为空。我不太清楚为什么会出现这种情况。是否 000webhost 有某种设置不允许某人发布数据?

此外,我知道我正在使用已弃用的 java 方法,并且我的密码存储当前是多么不安全。我将来会修改它,但我首先想知道如何发布数据。

提前致谢!

最佳答案

HttpClient 现已弃用,因此您应该使用 HttpUrlConnection 来代替,将 post 请求发送到服务器。

创建一个新类,它将向您的服务器发送异步发布请求。

public class YourAyncClass extends AsyncTask<String, Void, String>{


    public YourAyncClass(Context c){

        this.context = c;
    }

    public SaveCampaign(){}

    protected void onPreExecute(){}

    @Override
    protected String doInBackground(String... arg0) {

        try{
            URL url = new URL("Your url here");             

            JSONObject urlParameters = new JSONObject();
            urlParameters.put("name", "John Doe");
            urlParameters.put("email", "john@doe.com");
            urlParameters.put("password", "xxxxxx");
            urlParameters.put("leagueId", "123-456");

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setConnectTimeout(15000);
            connection.setReadTimeout(15000);

            OutputStream os = connection.getOutputStream();
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
            writer.write(getPostDataString(urlParameters));
            writer.flush();
            writer.close();
            os.close();

            int responseCode = connection.getResponseCode();

            if (responseCode == HttpURLConnection.HTTP_OK) {

                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

                StringBuffer sb = new StringBuffer("");
                String line = "";

                while ((line = in.readLine()) != null) {

                    sb.append(line);
                    break;
                }

                in.close();
                return sb.toString();
            }
            else {
                return new String("New Exception : "+responseCode);
            }
        }
        catch(Exception e){
            return new String("Exception: " + e.getMessage());
        }
    }

    protected void onPostExecute(String result){

    }   


    /*This method changes the json object into url encoded key-value pair*/
    public String getPostDataString(JSONObject params) throws Exception {

        StringBuilder result = new StringBuilder();
        boolean first = true;

        Iterator<String> itr = params.keys();

        while(itr.hasNext()){

            String key= itr.next();
            Object value = params.get(key);

            if (first)
                first = false;
            else
                result.append("&");

            result.append(URLEncoder.encode(key, "UTF-8"));
            result.append("=");
            result.append(URLEncoder.encode(value.toString(), "UTF-8"));

        }
        return result.toString();
    }
}

现在,要在您的方法中使用此类,您需要在代码中实现以下代码:

new YourAsyncClass(context).execute();

上面的代码行调用AsyncTask类的execute()方法并开始执行对服务器的http调用。

关于java - $_POST 未从 Java 代码接收数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34541812/

相关文章:

javascript - "Like"系统PHP,使用AJAX

php - 从表中获取数据

java - Android 如何复制 EditText 可绘制背景?

java - String 方法 isEmpty 在 Android API Levels < 10 中真的不可用吗?

java - 适配器类错误。创建时不得附加 ViewHolder View

java - 如何在 Java 中选择 getter 和 setter

php - 如何获得一个空的关联数组?

php - 使用 PHP 检测股票 android 浏览器?

java - FrameLayout 无法转换为 AbsListView Layout Params

java - Spring+MyBatis异常: Mapped Statements collection does not contain value for