通过Json从java客户端发送变量到php服务器

时间:2012-09-16 12:09:24

标签: java php android json

我是Java和PHP的初学者 我正在开发一个有2个部分的应用程序:

Android客户端(Java)和PHP服务器。

我尝试了许多可用的教程,并阅读了用户所犯的错误,但未能成功!

这是我正在使用的教程之一: Java文件

package org.postandget;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class Main extends Activity {

TextView tv;
String text;

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

    tv  = (TextView)findViewById(R.id.textview);
    text    = "";

    try {
        postData();
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public void postData() throws JSONException{  
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://10.0.2.2/ReceiveLocation.php");
    JSONObject json = new JSONObject();

    try {
        // JSON data:
        json.put("name", "Fahmi Rahman");
        json.put("position", "sysdev");

        JSONArray postjson=new JSONArray();
        postjson.put(json);

        // Post the data:
        httppost.setHeader("json",json.toString());
        httppost.getParams().setParameter("jsonpost",postjson);

        // Execute HTTP Post Request
        System.out.print(json);
        HttpResponse response = httpclient.execute(httppost);

        // for JSON:
        if(response != null)
        {
            InputStream is = response.getEntity().getContent();

            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();

            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            text = sb.toString();
        }

        tv.setText(text);

    }catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }
}
}

这是php文件

<?php
include('ConnectionFunctions.php');
Connection(); 

$json = $_POST['jsonpost'];
echo "JSON: \n";
echo "--------------\n";
var_dump($json);
echo "\n\n";

$data = json_decode($json);
echo "Array: \n";
echo "--------------\n";
var_dump($data);
echo "\n\n";

$name = $data->name;
$pos = $data->position;
echo "Result: \n";
echo "--------------\n";
echo "Name     : ".$name."\n Position : ".$pos; 
 ?>

这是我运行php时出现的错误

  Notice: Undefined index: HTTP_JSON in C:\xampp\htdocs\ReceiveLocation.php on line 5
  JSON: -------------- NULL Array: -------------- NULL
  Notice: Trying to get property of non-object in C:\xampp\htdocs\ReceiveLocation.php   on   line 17

  Notice: Trying to get property of non-object in C:\xampp\htdocs\ReceiveLocation.php on   line 18
  Result: -------------- Name : Position : 

3 个答案:

答案 0 :(得分:0)

使用以下方法访问JSON数据:

$json = $_POST['jsonpost'];

答案 1 :(得分:0)

你试图访问php文件中的无效字段,它应该是

      $json = $_POST['jsonpost'];

OR

       $json = $_REQUEST['jsonpost'];

如果您计划使用数据进行数据库处理,请记住还要从php文件中的错误输入中对数据进行消毒。也可以从

更改您的localhost路径
     HttpPost httppost = new HttpPost("http://127.0.0.1/ReceiveLocation.php"); 

TO

     HttpPost httppost = new HttpPost("http://10.0.2.2/ReceiveLocation.php");

希望我帮助过。

答案 2 :(得分:0)

您的代码出现问题,JSON数据只会添加到标头中,而不会添加到HTTP请求的POST部分。

所以当你输出:

print_r(getallheaders());

$headers = getallheaders();

$json = json_decode($headers['json']);

print_r($json);

您应该会看到您的数据。我现在还没有修复,但我正在研究它。

相关问题