我希望在Java程序中接收数据并将json HTTP请求发送到PHP程序以进一步处理。 我编写了以下Java程序。
import java.io.IOException;
import java.util.Scanner;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
public class JSON_Test_1
{
public static void main(String args[]) throws IOException
{
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
Scanner obj = new Scanner(System.in);
System.out.print ("Name: ");
String name = obj.nextLine();
//create a new JSON object
JSONObject root = new JSONObject();
//put the variables in JSON oebject
root.put("name", name);
System.out.println(root.toJSONString());
try
{
HttpPost request = new HttpPost("http://localhost/Test/");
StringEntity params = new StringEntity(root.toString());
request.addHeader("content-type", "application/json");
request.setEntity(params);
httpClient.execute(request);
// handle response here...
}
catch (Exception ex)
{
// handle exception here
}
finally
{
httpClient.close();
}
}
}
任何人都可以帮助我理解如何解码PHP程序中的json对象。提前致谢。
答案 0 :(得分:1)
数据应位于php实例的请求输入/正文流中,您可以通过php://input访问该实例。
(字符串)json数据可以通过json_decode()
<?php
$data = json_decode( file_get_contents('php://input'), true );
echo $data['name'];