如何在JAVA中的HTTP Put中传递JSON正文

时间:2018-12-16 14:31:11

标签: java http http-put

有人可以向我解释如何在请求正文中传递JSON参数。 我正在使用HttpURLConnection创建连接,如下所示:

URL uri = null;
    HttpURLConnection con = null;
    try{
        uri = new URL(url); //URL is hardcoded as of now
        con = (HttpURLConnection) uri.openConnection();
        con.setRequestMethod(type); //type: POST, PUT, DELETE, GET
        con.setDoOutput(true);
        con.setDoInput(true);
        con.setConnectTimeout(60000); //60 secs
        con.setReadTimeout(60000); //60 secs
        con.setRequestProperty("Accept-Encoding", "application/json");
        con.setRequestProperty("Content-Type", "application/json");
        con.setRequestProperty("cache-control", "no-cache");
        con.setRequestProperty("Postman-Token", "448b7c42-61f1-4373-8a7d-80a0a4610b99");

        JSONObject reqBody = new JSONObject();
        reqBody.put("state", "4");
        System.out.println(reqBody);
        StringEntity params = new StringEntity(reqBody.toString());
         if( reqBody != null){  
                con.setDoInput(true);
                con.setDoOutput(true);
                DataOutputStream out = new  DataOutputStream(con.getOutputStream());

如何在此处放置请求正文?

1 个答案:

答案 0 :(得分:0)

用于指定请求的正文:

OutputStreamWriter wr = new OutputStreamWriter(con.getOutputStream());
wr.write(reqBody.toString());
wr.flush()