I want to receive data in a Java program and send a json HTTP request to a PHP program to process further. I have written the following Java program.
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();
}
}
}
Can anyone help me understand how can I decode the json object in the PHP program. Thanks in advance.