2017-09-01 64 views
0

我使用HttpURLConnection發送HTTP POST請求。有人能告訴我如何格式化數組參數併發送它們。以下是JSON中的請求Body參數。使用JSON參數作爲數組的Java HTTP POST請求

{ 
    "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,表示沒有內容。我將不勝感激任何幫助。

+0

的可能的複製[爪哇 - 通過POST方法容易地發送HTTP參數](https://stackoverflow.com/questions/4205980/java-sending-http-parameters-via-post-method-easily) – DamCx

+0

根據您的要求製作對象,然後使用Jackson的對象映射器將其轉換爲字符串。 –

回答

0

我推薦建立在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()); 
}