在Java中,通過HTTP協(xié)議發(fā)送POST請求時,參數(shù)可以以不同的形式進行傳遞。一種常見的方式是將參數(shù)以JSON的形式封裝在請求體中。
public static String sendPostRequest(String url, String json) throws Exception{ CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); // 設置請求頭,表明請求體中包含的是JSON格式的數(shù)據(jù) httpPost.setHeader("Content-type", "application/json;charset=utf-8"); StringEntity stringEntity = new StringEntity(json, "utf-8"); httpPost.setEntity(stringEntity); CloseableHttpResponse response = null; try{ response = httpClient.execute(httpPost); HttpEntity entity = response.getEntity(); String result = EntityUtils.toString(entity, "utf-8"); return result; }finally{ if(response != null){ response.close(); } httpClient.close(); } }
上述代碼使用Apache HttpClient庫發(fā)送POST請求,并將參數(shù)以JSON格式封裝在請求體中。其中,
httpPost.setHeader("Content-type", "application/json;charset=utf-8");用于設置請求頭,表明請求體中包含的是JSON格式的數(shù)據(jù)。
可以通過調(diào)用該方法,傳遞請求的URL以及要發(fā)送的JSON參數(shù),實現(xiàn)對應接口的調(diào)用。