在Java中,通过HTTP协议发送POST请求时,可以通过不同的形式传递参数。常见的方式是将参数以JSON的形式封装在请求体中。
public static String sendPostRequest(String url, String json) 抛出异常{ CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost httpPost = new HttpPost(url); // 设置请求头,表明请求体中包含JSON格式的数据 httpPost.setHeader("内容类型", "application/json;charset=utf-8"); StringEntity stringEntity = new StringEntity(json, "utf-8"); httpPost.setEntity(stringEntity); CloseableHttpResponse 响应 = null; 尝试{ 响应 = httpClient.execute(httpPost); HttpEntity实体=response.getEntity(); 字符串结果 = EntityUtils.toString(entity, "utf-8"); 返回结果; }最后{ 如果(响应!=空){ 响应.close(); } httpClient.close(); } }
以上代码使用Apache HttpClient库发送POST请求,并将参数以JSON格式封装在请求体中。其中,
httpPost.setHeader("Content-type", "application/json;charset=utf-8");用于设置请求头,表示请求体中包含JSON格式的数据。
调用该方法,传入请求的URL和需要发送的JSON参数,即可调用相应的接口。