最近项目中遇到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

最新文章

  1. php组合
  2. 新版markdown功能发布!支持github flavored markdown!
  3. java -jar jenkins.war
  4. 面向服务的体系结构(SOA)——(2)ESB介绍及职责
  5. ecshop搜索出现相关商品的效果滑动下拉效果
  6. js 数组 转
  7. matlab norm的使用
  8. css去除webkit内核的默认样式
  9. eclipse 集成maven插件
  10. 使用jquery ajaxForm提交表单
  11. Python中的 @staticmethod@classmethod方法
  12. Linux批量复制文件到文件夹
  13. Z-Stack - Modification of Zigbee Device Object for better network access management
  14. Mysql 查看连接数,状态 最大并发数
  15. 【MySQL (六) | 详细分析MySQL事务日志redo log】
  16. BZOJ4377 Kurs szybkiego czytania \ Luogu 3589[POI2015]KUR - 数学思维题
  17. keras可视化pydot graphviz问题
  18. 二、Delphi10.3在不下载文件情况下读取网站文件大小等信息
  19. 将React Native集成至Android原生应用
  20. 智能指针--C++

热门文章

  1. 关于Intent Uri页面跳转
  2. EMQ X 系统调优和性能压测
  3. input标签file文件上传图片本地预览(转载)
  4. Execution failed for task ':app:checkDebugDuplicateClasses'解决办法
  5. C++ MFC学习 (三)
  6. python spacy [E050] Can't find model 'en_core_web_sm'
  7. 暴风影音16 v9.05.1202.1111 绿色版
  8. flannel 关闭SNAT
  9. css3的的新特性
  10. 新的学习历程-python2 print