JSON POST请求从服务器端使用Android中的HttpClient的Php接收?

时间:2018-01-04 11:49:59

标签: java php android json

我使用HttpClient使用PHP从Android应用发送JSON请求到服务器以接收请求。 我的代码:

以下MainActivity.java是我的AsyncTask

class AsyncT extends AsyncTask<Void, Void, Void> {
        @Override
        protected Void doInBackground(Void... voids) {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("https://test1.intuitionsoftwares.com/paytm/name2.php");

            try {

                JSONObject jsonobj = new JSONObject();
                jsonobj.put("name", "Suraj");
                jsonobj.put("age", "25");

                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
                nameValuePairs.add(new BasicNameValuePair("req", jsonobj.toString()));

                Log.e("mainToPost", "mainToPost" + nameValuePairs.toString());

               httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                HttpResponse response = httpclient.execute(httppost);
                InputStream inputStream = response.getEntity().getContent();
                InputStreamToStringExample str = new InputStreamToStringExample();
                responseServer = str.getStringFromInputStream(inputStream);
                Log.e("response", "response -----" + responseServer);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            super.onPostExecute(aVoid);    
            txt.setText(responseServer);
        }
    }

我的Php代码低于(name2.php):

    <?php
header('Content-Type: application/json');
$content = trim(file_get_contents("php://input")); 
$get = json_decode($content);
//Process the JSON.
$name = $get->name;
$age = $get->age;
$myJSON = json_encode($get);
//echo json_encode($name);
echo $name;
echo $age;
?>

所以,我需要显示JSON我发送给link: https://test1.intuitionsoftwares.com/paytm/name2.php

对我的phpAndroid代码更正的任何帮助都将不胜感激。

1 个答案:

答案 0 :(得分:0)

$get = json_decode($content);更改代码php

成为此代码$get = json_decode(stripslashes($_POST['req']));