简体   繁体   中英

Switch to POST method in java doesn't work

I can't understand how to switch to POST method in my HttpsURLConnection. On the debugger the request method is GET also after the setRequestMethod method. Can you tell me where is my mistake?

try {
                URL url=new URL("https://smartmates.herokuapp.com");
                HttpsURLConnection connection= (HttpsURLConnection) url.openConnection();
                connection.setRequestMethod("POST");
                connection.setDoInput(true);
                connection.setDoOutput(true);
                //I'll add some params here
                connection.disconnect();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

Thank you very much.

This is a piece of code that I use to POST the String mensaje and receiving rta.ToString() . I think that DoSetInput(true) is a mistake, because you want to send a POST (output) and, eventually, get a response.

 `
    String urlParametros = "<?xml version=\"1.0\"?>";
    urlParametros = urlParametros + mensaje;
    byte[] postDatos = urlParametros.getBytes(StandardCharsets.UTF_8);
    try {
        URL miurl = new URL(url);
        con = (HttpURLConnection) miurl.openConnection();
        con.setDoOutput(true);
        con.setRequestMethod("POST");
        //******…………..
        con.setRequestProperty("User-Agent", "Java client");
        con.setRequestProperty("Content-Type", "text/xml");
        try (DataOutputStream datos = new DataOutputStream(con.getOutputStream())) {
            datos.write(postDatos);
        }
        StringBuilder rta;
        try (BufferedReader entrada = new BufferedReader(
                new InputStreamReader(con.getInputStream()))) {
            String linea;
            rta = new StringBuilder();
            while ((linea = entrada.readLine()) != null) {
                rta.append(linea);
                rta.append(System.lineSeparator());
            }
        }
        return rta.toString();
    } finally {
        con.disconnect();
    }´

Hope it helps

Daniel

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