将数据从android发送到php并检索它

时间:2017-02-21 21:31:49

标签: java php android

我正在尝试将数据从我的Android应用程序发送到我的PHP代码并在那里检索它但是当我在我的网站上打印值时,它们显示的值为null。我为android尝试过的一些例子是:

OutputStream os = null;
        InputStream is = null;
        HttpURLConnection conn = null;
        try {
            //constants
            URL url = new URL(tempURL);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("message", "message");
            jsonObject.put("password", "password");
            String message = jsonObject.toString();
            Toast.makeText(this, "message = " + message, Toast.LENGTH_SHORT).show();

            conn = (HttpURLConnection) url.openConnection();
            conn.setReadTimeout(10000 /*milliseconds*/ );
            conn.setConnectTimeout(15000 /* milliseconds*/ );

            conn.setRequestMethod("POST");
            conn.setDoInput(true);
            conn.setDoOutput(true);
            conn.setFixedLengthStreamingMode(message.getBytes().length);

            //make some HTTP header nicety
            conn.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            conn.setRequestProperty("X-Requested-With", "XMLHttpRequest");

            //open
            conn.connect();

            //setup send
            os = new BufferedOutputStream(conn.getOutputStream());
            os.write(message.getBytes());
            //clean up
            os.flush();

            //do something with response
            is = conn.getInputStream();
            //String contentAsString = readIt(is,len);
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        } finally {
            //clean up
            try {
                os.close();
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            conn.disconnect();
        }

另一个是:

HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("http://samplewebsite.com/welcome.php");
            try {
                List<NameValuePair> nameValuePairs = new ArrayList<>(2);
                nameValuePairs.add(new BasicNameValuePair("state", "state"));
                nameValuePairs.add(new BasicNameValuePair("tag", "tag"));
                Toast.makeText(this, "nameValuePairs = " + nameValuePairs, Toast.LENGTH_LONG).show();
                httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                httpclient.execute(httppost);
//                msgTextField.setText(""); // clear text box
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
            } catch (IOException e) {
                // TODO Auto-generated catch block
            }

我在php中尝试过的一些代码是:

print_r("tag = " + $_POST['tag']);

并且

$json = file_get_contents('php://input');
$obj = json_decode($json);
$tag = $obj->{'tag'};
$state = $obj->{'state'};

请帮帮我,这些例子都不适合我。任何解决方案都会有帮助。谢谢!

1 个答案:

答案 0 :(得分:0)

我找到了如何从android发送数据到PHP的代码:

InputStream inputStream = null;
        String result = "";
        String url = [YOUR URL HERE];

        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            String json1 = "";
            JSONObject jsonObject = new JSONObject();
            jsonObject.accumulate("key", message);

            json1 = jsonObject.toString();
            StringEntity se = new StringEntity(json1);
            httpPost.setEntity(se);
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Content-type", "application/json");
            HttpResponse httpResponse = httpclient.execute(httpPost);

            inputStream = httpResponse.getEntity().getContent();

            // 10. convert inputstream to string
            if (inputStream != null) {
                result = convertInputStreamToString(inputStream);
                myJSON = result;
            } else {
                result = "Did not work!";
            }
        } catch (Exception e) {
               Log.d("InputStream", e.getLocalizedMessage());
}

方法convertInputStreamToString的代码是:

private static String convertInputStreamToString(InputStream inputStream) throws IOException {
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    String line = "";
    String result3 = "";
    while ((line = bufferedReader.readLine()) != null)
        result3 += line;

    inputStream.close();
    return result3;
}

我收到android的数据的PHP代码是:

$json = file_get_contents('php://input');
$obj = json_decode($json);
echo $obj->{'key'};

希望它有所帮助!