发送JSON从Java到PHP通过邮政 [英] Send JSON from Java to PHP through Post

查看:125
本文介绍了发送JSON从Java到PHP通过邮政的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做的是应该从平板电脑将数据发送到一个PHP Web服务的Andr​​oid程序。在code发送JSON的:

I am doing an Android program that is supposed to send data from the tablet to a PHP Web Service. The code for sending the JSON:

package com.example.shvalidation;

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.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;

public class MainMenuScreen extends Activity {
    //JSON Variables
    JSONParser jsonParser = new JSONParser();
    String pid;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_menu_layout);
        new TestThread().execute();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main_menu_layout, menu);
        return true;
    }

    public void PlantToDome(View view) {
        Intent intent = new Intent(this, SelectLocationScreen.class);
        startActivity(intent);
    }

    //Código del Web Service
    public class TestThread extends AsyncTask<Void, Void, Void> {
        ProgressDialog dialog;
        protected void onPreExecute() {
            dialog = ProgressDialog.show(MainMenuScreen.this, "Loading", "Loading data, please wait..");
        }

        private String convertStreamToString(InputStream is) {

            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();
                }
            }
            return sb.toString();
        }

        protected Void doInBackground(Void...args0) {
            try {
                HttpClient client = new DefaultHttpClient();
                HttpResponse response;
                HttpPost post = new HttpPost("http://192.168.1.101:8080/GetBook.php");

                JSONObject holder = new JSONObject();
                JSONObject euid = new JSONObject();
                euid.put("euid", 1);
                holder.accumulate("euids", euid);
                euid.put("euid", 2);
                holder.accumulate("euids", euid);

                post.setHeader("json", holder.toString());
                StringEntity se = new StringEntity(holder.toString());
                se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
                post.setEntity(se);
                response = client.execute(post);
                if (response != null) {
                    InputStream in = response.getEntity().getContent();

                    String a = convertStreamToString(in);
                    Log.i("Read from Server", a);
                }
            } catch (Exception e) {
                Log.d("error", e.toString());
            }
            return null;
        }

        protected void onPostExecute(Void unused) {
            dialog.dismiss();
        }
    }
}

PHP的Web服务:

The PHP Web Service:

<?php
    ob_start();

    var_dump(json_decode(file_get_contents('php://input')));

    $out = ob_get_contents();

    ob_end_clean();

    $f = fopen('out.txt', 'w+');

    fwrite($f, html_entity_decode($out));

    fclose($f);
?>

我已经尝试了不同的方法来获取JSON,但没有人对我工作过。也许计算器的人精能帮助我走出这一点,因为他们总是有,我已经有所有其他的问题。

I have tried different methods for getting the JSON, but none of them have worked for me. Maybe the fine people of StackOverflow can help me out with this, as they always have for every other problem that I've had.

推荐答案

从评论部分,它似乎只希望JSON被发送到你的PHP脚本。正常情况下,POST自检这PHP,并将其解压:

From the comments section, it appears you only want the JSON being sent to your PHP script. Normally, you post POST this to PHP, and extract it:

<?php
    print_r($_POST);
    $json_string = $_POST['message']; 
    $json = json_decode($json_string);
    print_r($json);
?>

再小的客户端的例子:

And then a small client example:

public static void main(String[] args) {

    String json = "{\"message\":\"This is a message\"}";

    HttpClient httpClient = new DefaultHttpClient();

    try {
        HttpPost request = new HttpPost("http://somesite.com/test.php");
        StringEntity params =new StringEntity("message=" + json);
        request.addHeader("content-type", "application/x-www-form-urlencoded");
        request.setEntity(params);
        HttpResponse response = httpClient.execute(request);

        // handle response here...

        System.out.println(org.apache.http.util.EntityUtils.toString(response.getEntity()));
        org.apache.http.util.EntityUtils.consume(response.getEntity());
    } catch (Exception ex) {
        // handle exception here
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

这个输出是:

The output of this is:

Array
(
    [message] => {"message":"This is a message"}
)
stdClass Object
(
    [message] => This is a message
)

这篇关于发送JSON从Java到PHP通过邮政的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆