java中post推送json格式字符串
2024-10-21 11:37:35
最近项目中遇到post推送json格式字符串,之前写过推送json数据,调用失败,才发现是直接推送字符串,只不过字符串是json的格式。
在postman中调用如下:
Java中代码如下:
/**
* 发送POST方法的请求
* @param url 发送请求的 URL
* @param jsonData 请求参数是Json格式字符串
* @return 响应结果
*/
public static String sendPostJsonStr(String url, String jsonData) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
HttpClient client = new HttpClient();
PostMethod postMethod = new PostMethod(url);
postMethod.addRequestHeader("Content-type", "application/json; charset=utf-8");
byte[] requestBytes = jsonData.getBytes("utf-8"); // 将参数转为二进制流
InputStream inputStream = new ByteArrayInputStream(requestBytes, 0, requestBytes.length);
// 请求体
RequestEntity requestEntity = new InputStreamRequestEntity(inputStream, requestBytes.length, "application/json; charset=utf-8");
postMethod.setRequestEntity(requestEntity); // 将参数放入请求体
client.executeMethod(postMethod);
inputStream = postMethod.getResponseBodyAsStream();
BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer stringBuffer = new StringBuffer();
String str= "";
while((str = br.readLine()) != null){
stringBuffer.append(str);
}
result=stringBuffer.toString();
} catch (Exception e) {
e.printStackTrace();
}
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
引用的jar包:commons-httpclient-3.1.jar、commons-logging-1.2.jar、commons-codec-1.9.jar
最新文章
- php组合
- 新版markdown功能发布!支持github flavored markdown!
- java -jar jenkins.war
- 面向服务的体系结构(SOA)——(2)ESB介绍及职责
- ecshop搜索出现相关商品的效果滑动下拉效果
- js 数组 转
- matlab norm的使用
- css去除webkit内核的默认样式
- eclipse 集成maven插件
- 使用jquery ajaxForm提交表单
- Python中的 @staticmethod@classmethod方法
- Linux批量复制文件到文件夹
- Z-Stack - Modification of Zigbee Device Object for better network access management
- Mysql 查看连接数,状态 最大并发数
- 【MySQL (六) | 详细分析MySQL事务日志redo log】
- BZOJ4377 Kurs szybkiego czytania \ Luogu 3589[POI2015]KUR - 数学思维题
- keras可视化pydot graphviz问题
- 二、Delphi10.3在不下载文件情况下读取网站文件大小等信息
- 将React Native集成至Android原生应用
- 智能指针--C++
热门文章
- 关于Intent Uri页面跳转
- EMQ X 系统调优和性能压测
- input标签file文件上传图片本地预览(转载)
- Execution failed for task ':app:checkDebugDuplicateClasses'解决办法
- C++ MFC学习 (三)
- python spacy [E050] Can't find model 'en_core_web_sm'
- 暴风影音16 v9.05.1202.1111 绿色版
- flannel 关闭SNAT
- css3的的新特性
- 新的学习历程-python2 print