分享web开发知识

注册/登录|最近发布|今日推荐

主页 IT知识网页技术软件开发前端开发代码编程运营维护技术分享教程案例
当前位置:首页 > 技术分享

HttpPost请求将json作为请求体传入的简单处理方法

发布时间:2023-09-06 01:26责任编辑:沈小雨关键词:jsjson

通过httpclient的post方法发送json参数进行接口测试。借鉴知乎上“云层”的提供的方法。

作者:云层
链接:https://www.zhihu.com/question/30878548/answer/121149629
来源:知乎
把要发送的json作为字符串传入body即可
 1 public static String sendHttpPost(String url, String body) throws Exception { 2 CloseableHttpClient httpClient = HttpClients.createDefault(); 3 HttpPost httpPost = new HttpPost(url); 4 httpPost.addHeader("Content-Type", "application/json"); 5 httpPost.setEntity(new StringEntity(body)); 6 ?7 CloseableHttpResponse response = httpClient.execute(httpPost); 8 System.out.println(response.getStatusLine().getStatusCode() + "\n"); 9 HttpEntity entity = response.getEntity();10 String responseContent = EntityUtils.toString(entity, "UTF-8"); 11 System.out.println(responseContent);12 13 response.close();14 httpClient.close();15 return responseContent;16 }

我的测试代码示例:

 1 ????public static void main(String[] args) { 2 ????????//测试公司的API接口,将json当做一个字符串传入httppost的请求体 3 ????????String result = null; 4 ????????HttpClient client = HttpClients.createDefault(); 5 ????????URIBuilder builder = new URIBuilder(); 6 ????????URI uri = null; 7 ????????try { 8 ????????????uri = builder.setScheme("http") 9 ??????????????????????.setHost("xxx.xxx.xxx.xxx:xxxx")10 ??????????????????????.setPath("/api/authorize/login")11 ??????????????????????.build();12 ????????????13 ????????????HttpPost post = new HttpPost(uri);14 ????????????//设置请求头15 ????????????post.setHeader("Content-Type", "application/json");16 ????????????String body = "{\"Key\": \"\",\"Secret\": \"\"}";17 ????????????//设置请求体18 ????????????post.setEntity(new StringEntity(body));19 ????????????//获取返回信息20 ????????????HttpResponse response = client.execute(post);21 ????????????result = response.toString();22 ????????} catch (Exception e) {23 ????????????System.out.println("接口请求失败"+e.getStackTrace());24 ????????}25 ????????System.out.println(result);26 ????}

HttpPost请求将json作为请求体传入的简单处理方法

原文地址:http://www.cnblogs.com/mambahyw/p/7875142.html

知识推荐

我的编程学习网——分享web前端后端开发技术知识。 垃圾信息处理邮箱 tousu563@163.com 网站地图
icp备案号 闽ICP备2023006418号-8 不良信息举报平台 互联网安全管理备案 Copyright 2023 www.wodecom.cn All Rights Reserved