简体   繁体   中英

send a variable from java client to php server via Json

I am a beginner in both Java and PHP I am working on an app that has 2 part:

Android client(Java) both and PHP server.

I tried many of the available tutorials and read about mistakes users made but failed to succeed in any!

This is one of the tutorials I am using: Java File

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
    }
}
}

this is the php file

<?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; 
 ?>

this is the error that appears when i run the 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 : 

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

$json = $_POST['jsonpost'];

You were trying to access an invalid field in your php file, it should have been

      $json = $_POST['jsonpost'];

OR

       $json = $_REQUEST['jsonpost'];

Remember to also sterilize your data from bad input in your php file if you plan to do database work with the data. ALso maybe your localhost path should be changed from

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

TO

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

Hope i helped.

You have a Problem with your code, JSON Data is only added to the header and not to the POST Section of HTTP Request.

So when you output:

print_r(getallheaders());

$headers = getallheaders();

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

print_r($json);

You should see your data. I right now have not a fix, but i am working on it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM