How to send java post information to a php page?

Asked

Viewed 1,841 times

1

I’m facing a problem that I don’t know how to solve right now. To put it bluntly, I’m having trouble sending data in json to a php page through a java application. Basically, I have a php page that receives the data through the POST method and created a java class 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 take the value on the php page from the code snippet filter_input(INPUT_POST, "user") , only that in the java application I do not insert this "user" identity in the information I want to send. Therefore, there is no way that the php page "catch" the value that the java application is sending. Does anyone have any idea how to solve this problem? Thanks in advance!
PHP page:

<?php

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

    if($_SERVER['REQUEST_METHOD'] == "POST"){
        $controller->cadastrarUsuario(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;
    }
}

2 answers

1

To send and receive data create this class in your project:

public class Conexao {

public static String postDados(String urlUsuario, String parametrosUsuario) {
    URL url;
    HttpURLConnection connection = null;

    try {

        url = new URL(urlUsuario);
        connection = (HttpURLConnection) url.openConnection();

        connection.setRequestMethod("POST");

        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

        connection.setRequestProperty("Content-Lenght", "" + Integer.toString(parametrosUsuario.getBytes().length));

        connection.setRequestProperty("Content-Language", "pt-BR");

        //connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");

        connection.setUseCaches(false);
        connection.setDoInput(true);
        connection.setDoOutput(true);

        //Envio
        OutputStreamWriter outPutStream = new OutputStreamWriter(connection.getOutputStream(), "utf-8");
        outPutStream.write(parametrosUsuario);
        outPutStream.flush();
        outPutStream.close();
        //Recepção
        InputStream inputStream = connection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));

        String linha;
        StringBuffer resposta = new StringBuffer();

        while((linha = bufferedReader.readLine()) != null) {
         resposta.append(linha);
            resposta.append('\r');
        }

        bufferedReader.close();

        return resposta.toString();

    } catch (Exception erro) {

        return  null;
    } finally {

        if(connection != null) {
            connection.disconnect();
        }
    }
}
}

To call her in your project do:

public class main extends AppCompatActivity {

String url = "";
String parametros = "";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    //Se fosse um get bastava colocar no final da string url o ?nome=seuget
    url = "url do arquivo php";

    //parâmetros do post
    parametros = "texto=" + "123";

    new main.solicita().execute(url);

   }

    private class solicita extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... urls) {

        return Conexao.postDados(urls[0], parametros);
    }

    @Override
    protected void onPostExecute(String resultado) {

        //A string resultado tem os dados vindos do seu arquivo php

    }
}
}

0

    //add reuqest header
    con.setRequestMethod("POST");
    con.setRequestProperty("User-Agent", USER_AGENT);
    con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

    String urlParameters = "user=Joao";

    // Send post request
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(urlParameters);
    wr.flush();
    wr.close();

https://www.mkyong.com/java/how-to-send-http-request-getpost-in-java/

  • I found this researching.

  • I tried it here and it didn’t work buddy. Thanks for trying to help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.