【问题标题】:HTTP POST Request in Java with JSON parameters as array使用 JSON 参数作为数组的 Java 中的 HTTP POST 请求
【发布时间】:2017-09-01 09:36:19
【问题描述】:

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

{
  "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,表示没有内容。我将不胜感激。

【问题讨论】:

标签: java json rest http


【解决方案1】:

我建议尝试基于 apache http api 构建的 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());
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-03
    • 1970-01-01
    • 1970-01-01
    • 2017-04-07
    • 1970-01-01
    • 2018-09-21
    相关资源
    最近更新 更多