dousao8152 2017-03-24 09:16
浏览 102

使用json字符串将数据从java发送到php不起作用

I have in my java application some data that I want to send them to php using json to insert them later in database. the problem is with the json string.

Main.java

String args = "{\"nom\":\""+hostName+"\",\"host_name\":\""+hostName+"\", \"os_name\":\""+nameOS+"\",\"os_type\":\""+osType+"\",\"os_version\":\""+osVersion+"\"}";
Cpu.main(args);

Cpu.java

package webservice;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

public class Cpu {

    public static void main(String args) {

        try {
            // make json string, try also hamburger

            // send as http get request
            URL url = new URL("http://localhost:8080/parc/index.php?order=" + args);
            URLConnection conn = url.openConnection();

            // Get the response
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = rd.readLine()) != null) {
                System.out.println(line);
            }
            rd.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

PHPFILE.php

    <?php
$order = $_GET["order"];
$obj = json_decode($order);
$nom = $obj->{"nom"};
$host_name = $obj->{"host_name"};
$os_name = $obj->{"os_name"};
$os_type = $obj->{"os_type"};
$os_version = $obj->{"os_version"};
                echo $host_name;
            echo json_last_error(); // 4 (JSON_ERROR_SYNTAX)
echo json_last_error_msg(); // unexpected character 
$array = array("nom" => $nom, "host_name" => $host_name, "os_name" => $os_name, "os_type" => $os_type, "os_version" => $os_version);
echo json_encode($array);

?>

Now I think that the problem with the json string format wich is "args" because when I change the variables hostname, os_type... like this : (String json = "{\"name\":\"Frank\",\"food\":\"pizza\",\"quantity\":3}";) (from a tutorial) it works normally.

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 如何实验stm32主通道和互补通道独立输出
    • ¥30 这是哪个作者做的宝宝起名网站
    • ¥60 版本过低apk如何修改可以兼容新的安卓系统
    • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
    • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
    • ¥50 有数据,怎么用matlab求全要素生产率
    • ¥15 TI的insta-spin例程
    • ¥15 完成下列问题完成下列问题
    • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
    • ¥15 YoloV5 第三方库的版本对照问题