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

1

I'm facing a problem that at the moment I do not know how to solve. Being straightforward, I'm having trouble sending through a java application the data in json for 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 enter the "handle" that is requested in the php page. As you can see, I get the value in the page in php by the filter_input(INPUT_POST, "user") code snippet, except that 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! Home 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 submitting 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;
    }
}
    
asked by anonymous 20.06.2017 / 21:43

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 it on 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

    }
}
}
    
18.03.2018 / 04:22
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();

link

    
20.06.2017 / 21:59