Java http请求json数据

public static String sendJson(String url, String json) {
String returnValue = "调用接口失败";
CloseableHttpClient httpClient = HttpClients.createDefault();
ResponseHandler<String> responseHandler = new BasicResponseHandler();
try{
//第一步:创建HttpClient对象
httpClient = HttpClients.createDefault();

//第二步:创建httpPost对象
HttpPost httpPost = new HttpPost(url);

//第三步:给httpPost设置JSON格式的参数
StringEntity requestEntity = new StringEntity(json,"utf-8");
requestEntity.setContentEncoding("UTF-8");
httpPost.setHeader("Content-type", "application/json");
httpPost.setEntity(requestEntity);

//第四步:发送HttpPost请求,获取返回值
returnValue = httpClient.execute(httpPost,responseHandler); //调接口获取返回值时,必须用此方法

}
catch(Exception e){
e.printStackTrace();
}finally {
try {
httpClient.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//第五步:处理返回值
return returnValue;
}
posted @   丿狂奔的蜗牛  阅读(208)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示