简体   繁体   中英

How to send via post in java an information to a php page?

I am having trouble sending through a java application the data to a page in php. Basically, I have a page in php that receives the data through the POST method and created a class in java that sends this data via post. The problem is that in java I do not insert the identifier that is requested in the php page. As you can see, I get the value on the page in php by the filter_input (INPUT_POST, "user") code snippet, but in the java application I do not enter this "user" identifier in the information I want to send. So, there's no way the php page "picks up" the value that the java application is sending. Anyone have any ideas how to solve this problem? Thank you very much in advance!
Page PHP:

<?php

    require_once './vendor/autoload.php';
    $controller = new App\CWS\Controller();

    if($_SERVER['REQUEST_METHOD'] == "POST"){
        $controller->registerUser(filter_input(INPUT_POST, "user"));
    }

?>

Class responsible for connecting and sending data in the Java application:

public class WebClient {
    public String post(String json) {
        try {
            URL url = new URL("http://localhost//CWS//cadastrar_usuario.php");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Content-type", "application/json");
            connection.setRequestProperty("Accept", "application/json");

            connection.setDoOutput(true);

            PrintStream output = new PrintStream(connection.getOutputStream());
            output.println(json);

            connection.connect();

            Scanner scanner = new Scanner(connection.getInputStream());
            String resposta = scanner.next();
            return resposta;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
        PrintStream output = new PrintStream(connection.getOutputStream());
        output.println(json);

With this you are sending the data as JSON encoded text to the server. Whatever is in the JSON string at this point will be sent. If you have not put the data for "user" in the JSON, you have to put it before sending it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM