我需要将一些数据从我的Android应用程序传递到我的PHP服务器。
这是我的代码
public class BackgroundDataLoader extends AsyncTask<Void, Void, String>{
@Override
protected String doInBackground(Void... params) {
JSONObject jsObj=new JSONObject();
try {
jsObj.put("ID", 1);
jsObj.put("Name", "Shashika");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url+"/data.php");
try {
StringEntity se=new StringEntity(jsObj.toString());
se.setContentType("application/json;charset=UTF-8");
se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=UTF-8"));
httppost.setEntity(se);
} catch (UnsupportedEncodingException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
JSONArray finalResult = null;
String json = null;
HttpResponse response = null;
String text = null;
JSONArray jsonArray;
JSONObject jsonObject = null;
// Execute HTTP Post Request
try {
response = httpclient.execute(httppost);
int statusCode=response.getStatusLine().getStatusCode();
if(statusCode==200){
HttpEntity entity=response.getEntity();
text=EntityUtils.toString(entity);
}
else{
return "error "+response.getStatusLine().getStatusCode();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
jsonArray= new JSONArray(text);
//text=jsonArray.getJSONObject(0).getJSONArray(name);
text=jsonArray.getString(0);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String tag=text;
Log.d(tag, text);
return text;
}
现在我需要在服务器的php文件中将此数据作为JSON对象读取。如何在服务器的php文件中读取这些数据?
答案 0 :(得分:0)
如果你专注于php而不是android代码,那确实会很好。因此,我假设你正在根据正常的HTTP请求发布你的JSON数据。如果没有,请另外说明。
您应该对以下代码段感到满意:
// get the POSTed data
$json = file_get_contents('php://input');
// decode the JSON formatted data
$obj = json_decode($json);
// such that - on success - $obj is either null,true,false, an array or a stdClass object
// assuming you POST {"my_key":"my_value"} you can access this as follows
$obj->my_key == 'my_value'; // -> true
// or if you pass the according Options to json_decode to enforce using associative arrays
$obj['my_key'] == 'my_value'; // ->true
基本上你会在官方PHP JSON documentation找到更多详细信息,恰好是google第一次点击'php json'。
我进一步假设您知道如何在php中进行一些基本编码。