【问题标题】:$_POST not receiving data from Java code$_POST 未从 Java 代码接收数据
【发布时间】:2015-12-31 05:56:35
【问题描述】:

我是一个新手,正在为 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 方法以及我的密码存储目前是多么不安全。我将来会修改它,但我首先想知道如何发布数据。

提前致谢!

【问题讨论】:

    标签: java php android sql


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-25
      • 2018-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多