简体   繁体   English

无法将数据从Android发送到PHP JSON

[英]Unable to send data from Android to PHP JSON

Below is the method in which I use to send data to PHP 下面是我用来向PHP发送数据的方法

public String createUser(String url,String method,List<Pair<String, String>> params){
        //Making Http request
        HttpURLConnection httpURLConnection = null;
        StringBuffer response = null;
        String lineEnd = "\r\n";

        try{
            if(method.equals("POST")){
                URL urlPost = new URL(url);
                httpURLConnection = (HttpURLConnection) urlPost.openConnection();
                httpURLConnection.setDoOutput(true); //defaults request method to POST
                httpURLConnection.setDoInput(true);  //allow input to this HttpURLConnection
                httpURLConnection.setUseCaches(false);
                httpURLConnection.setRequestMethod("POST");
                //httpURLConnection.setRequestProperty("Content-Type","application/json");
                //httpURLConnection.setRequestProperty("Host", "192.168.0.101");
                httpURLConnection.connect();
                DataOutputStream wr = new DataOutputStream(httpURLConnection.getOutputStream());
                wr.writeBytes(params.toString());
                //wr.writeBytes("user_email="+userEmailText);
                //wr.writeBytes(lineEnd);
                wr.flush(); //flush the stream when we're finished writing to make sure all bytes get to their destination
                wr.close();
                InputStream is = httpURLConnection.getInputStream();
                BufferedReader rd = new BufferedReader(new InputStreamReader(is));
                String line;
                response = new StringBuffer();
                while((line = rd.readLine()) != null) {
                    response.append(line);
                    response.append('\r');
                }
            }

        } catch (ProtocolException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return response.toString();

    }

In my AsyncTask class: 在我的AsyncTask类中:

 params.add(new Pair<>("user_name", userNameText));
 params.add(new Pair<>("user_email", userEmailText));
  HttpHandler sh = new HttpHandler();
            String jsonStrUserCreation = sh.createUser(url,"POST",params);
            System.out.println("userNameText: " + userNameText);
            System.out.println("userEmailText: " + userEmailText);
            Log.e(TAG, "Response from userCreationURL: " + jsonStrUserCreation);
            try{
                JSONObject jsonObj = new JSONObject(jsonStrUserCreation);
            } catch (JSONException e) {
                e.printStackTrace();
            }

Below is my PHP code: 下面是我的PHP代码:

<?php 

    require_once 'connecttodb.php';
    $db = new DB();
    $con = $db->db_connect();

    if(isset($_POST['user_name']) && isset($_POST['user_email'])){
        $user_name = $_POST['user_name'];
        $user_email = $_POST['user_email'];
        $sql = "INSERT INTO user_details(user_name,user_email) VALUES('$user_name','$user_email')";
        $run = mysqli_query($con,$sql);
        if($run){
            $response["success"] = 1;
            $response["message"] = "Account successfully created";
            echo json_encode($response);
        }else{
            $response["success"] = 0;
            $response["message"] = "Account failed to be created";
            echo json_encode($response);
        }
    }else{
            $response["success"] = 2;
            $response["message"] = "Failed to run inner code";
            echo json_encode($response);
    }

The script always return "Failed to run inner code" when I have passed in the values for user_name and user_email. 当我传入user_name和user_email的值时,脚本始终返回“无法运行内部代码”。

Found the solution as below. 找到解决方案如下。 Make sure that your string is in the format below 确保您的字符串采用以下格式

String urlParameters = "user_name="+userNameText+"&user_email="+userEmailText;

And then call it as below: 然后将其命名如下:

sh.createUser(url,urlParameters);

You will see the magic. 你会看到魔力。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM