Java中的HTTP POST请求,JSON参数为数组

时间:2017-09-01 09:36:20

标签: java json rest http

我使用HttpURLConnection发送了一个HTTP POST请求。有人能告诉我如何格式化数组参数并发送它们。以下是JSON中的请求Body参数。

{
  "data": [
    {
      "type": "enrolled-courses",
      "id": "ea210647-aa59-49c1-85d1-5cae0ea6eed0"
    }
  ]
}

目前这是我的代码。

 private void sendPost() throws Exception {


             URL url = new URL("my_url");
                Map<String,Object> params = new LinkedHashMap<>();
                params.put("type", "courses");
                params.put("id", "19cfa424-b215-4c39-ac13-0491f1a5415d");           

                StringBuilder postData = new StringBuilder();
                for (Map.Entry<String,Object> param : params.entrySet()) {
                    if (postData.length() != 0) postData.append('&');
                    postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
                    postData.append('=');
                    postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
                }
                byte[] postDataBytes = postData.toString().getBytes("UTF-8");

                HttpURLConnection conn = (HttpURLConnection)url.openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                conn.setRequestProperty("Content-Length", String.valueOf(postDataBytes.length));
                conn.setDoOutput(true);
                conn.getOutputStream().write(postDataBytes);

                Reader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));

                for (int c; (c = in.read()) >= 0;)
                    System.out.print((char)c);
            }

响应代码为204,表示没有内容。我将不胜感激任何帮助。

1 个答案:

答案 0 :(得分:0)

我建议在apache http api上构建try http-request

private static final HttpRequest<String.class> HTTP_REQUEST = 
      HttpRequestBuilder.createPost(YOUR_URI, String.class)
           .responseDeserializer(ResponseDeserializer.ignorableDeserializer())
           .build();

private void sendPost(){
      Map<String, String> params = new HashMap<>();
      params.put("type", "courses");
      params.put("id", "19cfa424-b215-4c39-ac13-0491f1a5415d"); 

      ResponseHandler<String> rh = HTTP_REQUEST.execute(params);
      rh.ifSuccess(this::whenSuccess).otherwise(this::whenNotSuccess);
}

privat void whenSuccess(ResponseHandler<String> rh){
    if(rh.hasContent()){
       System.out.println(rh.get()); // prints response
    }else{
       System.out.println("Response is not available. Status code is: " + rh.getStatusCode());
    }
}

privat void whenNotSuccess(ResponseHandler<String> rh){
  System.out.println(rh.getErrorText());
}