最近用到java连url用json参数,记录一下代码:
public static void main(String args[]) {
String url = "https://api.xxx.xxx.com";
String params = "{\"param1\": \"123456\",\"param2\": \"T123456\"}";
Map requestHeader = new HashMap<>();
requestHeader.put("Content-Type", "application/json");
String response = null;
try {
response = send(url, params, "UTF-8", requestHeader);
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.print(response);
}
public static String send(String url, String jsonString, String encoding, Map requestHeader) throws ParseException, IOException{
String body = "";
CloseableHttpClient client = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
//装填json参数
StringEntity s = new StringEntity(jsonString, "utf-8");
httpPost.setEntity(s);
System.out.println("URL:"+url);
if (MapUtil.isNotEmpty(requestHeader)) {
for (Iterator it = requestHeader.entrySet().iterator(); it.hasNext();) {
Map.Entry entry = (Map.Entry)it.next();
httpPost.setHeader((String) entry.getKey(), (String) entry.getValue());
}
}
CloseableHttpResponse response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity != null) {
body = EntityUtils.toString(entity, encoding);
}
EntityUtils.consume(entity);
response.close();
return body;
}
本文分享了一个使用Java向指定URL发送带有JSON参数的POST请求的代码示例。通过HttpClients和HttpPost实现,展示了如何设置请求头、填充JSON参数,并获取响应结果。
2109

被折叠的 条评论
为什么被折叠?



