java - 通过 Post 将 JSON 从 Java 发送到 PHP

标签 java php android

我正在编写一个 Android 程序,该程序应该将数据从平板电脑发送到 PHP Web 服务。发送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 网络服务:

<?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,但没有一种对我有用。也许 StackOverflow 的优秀人员可以帮助我解决这个问题,因为他们总是为我遇到的所有其他问题提供帮助。

最佳答案

从评论部分来看,您似乎只希望将 JSON 发送到您的 PHP 脚本。通常,您将此 POST 发布到 PHP,然后提取它:

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

然后是一个小客户端示例:

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();
    }
}

这个的输出是:

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

关于java - 通过 Post 将 JSON 从 Java 发送到 PHP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14983521/

相关文章:

用于上下音量键的Android BroadCastReceiver

java - 构建 JPA Criteria API 查询 - 按集合中的元素数排序

php - SHA-1 哈希可以是纯数字吗?

php - 检查用户名/电子邮件可用性设计问题

php - 商户信息无效 : 10002-You do not have permissions to make this API call

Android Studio 3.5无法打开以前版本的项目

android - 在 Android 注释中,我想知道 @background 何时完成

java - 获取子节点之前的父节点的字符串内容

java - 构建: Jasmine-maven-plugin error

用于在 Youtube 中搜索特定主题评论的 Java 代码