Making PUT request with JSON data using HttpURLConnection is not working

后端 未结 1 1249
醉话见心
醉话见心 2020-12-30 08:56

I\'m trying to make PUT request with JSON data using HttpURLConnection in Java. The way I do it doesn\'t work. I get no errors so I don\'t know what the problem

相关标签:
1条回答
  • 2020-12-30 09:54

    The Sun (Oracle) implementation of HttpURLConnection caches the content of your post unless you tell it to be in streaming mode. The content will be sent if you start interaction with the response such as:

    hurl.getResponseCode();
    

    Also, according to RFC 4627 you can not use single quotes in your json (although some implementations seem to not care).

    So, change your payload to:

    String payload = "{\"pos\":{\"left\":45,\"top\":45}}";
    

    This example works for me

    public class HttpPut {
        public static void main(String[] args) throws Exception {
            Random random = new Random();
            URL url = new URL("http://fltspc.itu.dk/widget/515318fe17450f312b00153d/");
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("PUT");
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type", "application/json");
            connection.setRequestProperty("Accept", "application/json");
            OutputStreamWriter osw = new OutputStreamWriter(connection.getOutputStream());
            osw.write(String.format("{\"pos\":{\"left\":%1$d,\"top\":%2$d}}", random.nextInt(30), random.nextInt(20)));
            osw.flush();
            osw.close();
            System.err.println(connection.getResponseCode());
        }
    }
    
    0 讨论(0)
提交回复
热议问题