我在我的java应用程序中有一些数据,我想使用json将它们发送到php,以便稍后在数据库中插入它们。问题出在json字符串上。
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);
?>
现在我认为json字符串格式的问题是“args”,因为当我更改变量hostname
时,os_type
...就像这样:( String json = "{\"name\":\"Frank\",\"food\":\"pizza\",\"quantity\":3}";
)(从教程中)它正常工作。