繁体   English   中英

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

[英]Sending data from android to php and retrieving it

我正在尝试将数据从我的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'};

请帮助我,这些例子对我来说都没有。 任何解决方案都会有所帮助。 谢谢!

我发现了以下代码,说明如何将数据从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;
}

我的php代码从android接收数据是:

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

希望能帮助到你!

暂无
暂无

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

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