如何在php服务器上接收JSON对象

如何在php服务器上接收JSON对象,php,android,json,Php,Android,Json,我的Android应用程序需要将数据发送到PHP服务器。我是PHP新手,不知道如何在服务器上接收JSON和解码对象。如果有人能让我启动,那将是很大的帮助 JSONObject json = new JSONObject(); try { json.put("dog", "cat"); } catch (JSONException e1) { // TODO Auto-generated catch block e1.printStackTrace(); } Ht

我的Android应用程序需要将数据发送到PHP服务器。我是PHP新手,不知道如何在服务器上接收JSON和解码对象。如果有人能让我启动,那将是很大的帮助

JSONObject json = new JSONObject();

try 
{
    json.put("dog", "cat");
} 
catch (JSONException e1) 
{
    // TODO Auto-generated catch block
    e1.printStackTrace();
}

HttpURLConnection urlConnection = null;
try 
{
    URL url = new URL("http://10.0.2.2/server.php");
    urlConnection = (HttpURLConnection)url.openConnection();
    urlConnection.setRequestProperty("Content-Type", "application/json");
    urlConnection.setRequestProperty("Accept", "application/json");
    urlConnection.setRequestMethod("POST");         
    urlConnection.setDoOutput(true);
    OutputStreamWriter os = new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8");
    os.write(json.toString());
    os.close();
}

举个例子。你的MyActivity课程

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.mylyout);

            new PostToServer().execute();

}

class PostToServer extends AsyncTask<String, String, String> {


    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(MyActivity.this);
        pDialog.setMessage(getString(R.string.progdata));
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(true);
        pDialog.show();
    }


    protected String doInBackground(String... args) {

        String cat = "mycat";
        String dog = "mydog";

        HttpParams httpParameters = new BasicHttpParams();

        HttpClient client = new DefaultHttpClient(httpParameters);
        client.getParams().setParameter("http.protocol.version", HttpVersion.HTTP_1_1);
        client.getParams().setParameter("http.socket.timeout", 2000);
        client.getParams().setParameter("http.protocol.content-charset", HTTP.UTF_8);
        httpParameters.setBooleanParameter("http.protocol.expect-continue", false);
        HttpPost request = new HttpPost("http://yourserver/your.php);
        request.getParams().setParameter("http.socket.timeout", 5000);

        List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
        postParameters.add(new BasicNameValuePair("cat", cat));
        postParameters.add(new BasicNameValuePair("dog", dog));

        try {
        UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(postParameters, HTTP.UTF_8);
        request.setEntity(formEntity);

        HttpResponse response = client.execute(request);

        in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        StringBuffer sb = new StringBuffer("");
        String line = "";
        while ((line = in.readLine()) != null) {
            sb.append(line);
        }
        in.close();
        String result = sb.toString();

        String delimso = "[;]+";
        String[] resultxxx = result.split(delimso);

         if( resultxxx[0].equals("1")) {


            // successfully updated
            //to do some

        }else {

            // unsuccessfully updated
            //to do some
        }

             } catch (ClientProtocolException e) {
               // TODO Auto-generated catch block
               e.printStackTrace();

              } catch (IOException e) {
                   // TODO Auto-generated catch block
                   e.printStackTrace();

                  }


        return null;
    }           



    protected void onPostExecute(String file_url) {
        // dismiss the dialog once product uupdated
        pDialog.dismiss();
    }
}
@覆盖
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.mylyut);
新建PostToServer().execute();
}
类PostToServer扩展了AsyncTask{
@凌驾
受保护的void onPreExecute(){
super.onPreExecute();
pDialog=newprogressdialog(MyActivity.this);
setMessage(getString(R.string.progdata));
pDialog.setUndeterminate(假);
pDialog.setCancelable(真);
pDialog.show();
}
受保护的字符串doInBackground(字符串…args){
字符串cat=“mycat”;
字符串dog=“mydog”;
HttpParams httpParameters=新的BasicHttpParams();
HttpClient=新的默认HttpClient(httpParameters);
client.getParams().setParameter(“http.protocol.version”,HttpVersion.http_1_1);
client.getParams().setParameter(“http.socket.timeout”,2000);
client.getParams().setParameter(“http.protocol.content字符集”,http.UTF_8);
httpParameters.setBooleanParameter(“http.protocol.expect continue”,false);
HttpPost请求=新建HttpPost(“http://yourserver/your.php);
request.getParams().setParameter(“http.socket.timeout”,5000);
List postParameters=new ArrayList();
后参数。添加(新的BasicNameValuePair(“cat”,cat));
添加(新的BasicNameValuePair(“dog”,dog));
试一试{
UrlEncodedFormEntity formEntity=新的UrlEncodedFormEntity(后参数,HTTP.UTF_8);
请求。setEntity(formEntity);
HttpResponse response=client.execute(请求);
in=新的BufferedReader(新的InputStreamReader(response.getEntity().getContent());
StringBuffer sb=新的StringBuffer(“”);
字符串行=”;
而((line=in.readLine())!=null){
某人附加(行);
}
in.close();
字符串结果=sb.toString();
字符串delimso=“[;]+”;
字符串[]resultxxx=result.split(delimso);
如果(resultxxx[0]。等于(“1”)){
//成功更新
//做一些
}否则{
//更新失败
//做一些
}
}捕获(客户端协议例外e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
返回null;
}           
受保护的void onPostExecute(字符串文件\u url){
//产品更新后关闭对话框
pDialog.disclose();
}
}
服务器上的.php脚本

<?php


$cat = $_POST['cat'];
$dog = $_POST['dog'];

   //login to database

   //mysql operations $resttt
$result = mysql_query("$resttt");

$res="0;0";
if($result) { $res="1;0"; }               



echo $res;
?>

谢谢大家的帮助。我已经编写了一些代码,它正在运行。

PHP服务器脚本

    $msg = file_get_contents('php://input');
    $input = json_decode($msg,true);

现在json对象存储在$input变量中。

尝试从
var\u dump($\u POST)开始;
php://stdin
我已经试过了。我的问题仍然是如何在我的php服务器上接收android发送的数据?任何教程都会有很大帮助。我从4天起就一直坚持这一部分。我已经连接了数据库。但我没有收到任何数据。我如何接收数据?接收和解码json obje的正确方式是什么使用
$\u POST
php://stdin
我使用了$POST,例如:if(isset($POST))或if(isset($POST['dog'))。但是它们返回的是空的。$\u POST中没有任何内容。我曾两次提到
$\u POST
php://stdin
。您是否检查了后者?这是已弃用的HttpClient的用法。请获取HttpUrlConnection的示例。