$ _POST没有从Java代码

时间:2015-12-31 05:56:35

标签: java php android sql

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

我的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方法以及当前密码存储的不安全程度。我将来会修改它,但我首先想知道如何发布数据。

提前致谢!

1 个答案:

答案 0 :(得分:1)

现在不推荐使用

HttpClient ,因此您应该使用 HttpUrlConnection 来向服务器发送帖子请求。

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

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调用。