我使用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
。
对我的php
或Android
代码更正的任何帮助都将不胜感激。
答案 0 :(得分:0)
从$get = json_decode($content);
更改代码php
成为此代码$get = json_decode(stripslashes($_POST['req']));