Java 用HTTP的方式发送JSON报文请求
前言:
项目调用第三方接口时,通常是用socket或者http的通讯方式发送请求:http 为短连接,客户端发送请求都需要服务器端回送响应,请求结束后,主动释放链接。Socket为长连接:通常情况下Socket 连接就是 TCP 连接,因此 Socket 连接一旦建立,通讯双方开始互发数据内容,直到双方断开连接。下面介绍HTTP的方式发送和接收JSON报文。
需求:
用HTTP的方式,向URL为127.0.0.1:8888地址发送json报文,返回的结果也是json报文。
主要代码如下:
String resp= null;
JSONObject obj = new JSONObject();
obj.put("name", "张三");
obj.put("age", "");
String query = obj.toString();
log.info("发送到URL的报文为:");
log.info(query);
try {
URL url = new URL("http://127.0.0.1:8888"); //url地址 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type","application/json");
connection.connect(); try (OutputStream os = connection.getOutputStream()) {
os.write(query.getBytes("UTF-8"));
} try (BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()))) {
String lines;
StringBuffer sbf = new StringBuffer();
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), "utf-8");
sbf.append(lines);
}
log.info("返回来的报文:"+sbf.toString());
resp = sbf.toString(); }
connection.disconnect(); } catch (Exception e) {
e.printStackTrace();
}finally{
JSONObject json = (JSONObject)JSON.parse(resp);
}
网上还有一种拼json发送报文的方式,也把代码分享出来:
String resp = null;
String name = request.getParameter("userName");
String age = request.getParameter("userAge");
String query = "{\"name\":\""+name+"\",\"age\":\""+age+"\"}"; try {
URL url = new URL("http://10.10.10.110:8888"); //url地址 HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type","application/json");
connection.connect(); try (OutputStream os = connection.getOutputStream()) {
os.write(query.getBytes("UTF-8"));
} try (BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()))) {
String lines;
StringBuffer sbf = new StringBuffer();
while ((lines = reader.readLine()) != null) {
lines = new String(lines.getBytes(), "utf-8");
sbf.append(lines);
}
log.info("返回来的报文:"+sbf.toString());
resp = sbf.toString(); }
connection.disconnect(); } catch (Exception e) {
e.printStackTrace();
}finally{
JSONObject json = (JSONObject)JSON.parse(resp);
}
两种方式其实都是一样的。
Java 用HTTP的方式发送JSON报文请求的更多相关文章
- java 模拟http请求,通过流(stream)的方式,发送json数据和文件
发送端: /** * 以流的方式 * 发送文件和json对象 * * @return */ public static String doPostFileStreamAndJsonObj(String ...
- java使用POST发送soap报文请求webservice返回500错误解析
本文使用JAX-WS2.2编译webservice,并使用HttpUrlConnection的POST方式对wsdl发送soap报文进行请求返回数据, 对错误Server returned HTTP ...
- volley用法之 以post方式发送 json 参数
需求是这样 我们需要发送一个post请求向服务器要参数.要求是发送的post参数也要是json格式. 简单一点的是这样的: 如果要发送的是这样简单的json格式,我们可以简单的使用map来实现: Re ...
- ABAP接口之Http发送json报文
abap 调用http 发送 json 测试函数 SE11创建结构:zsmlscpnotice SE37创建函数:zqb_test_http_fuc1 FUNCTION zqb_test_http_f ...
- HttPclient 以post方式发送json
使用HttpClient 以POST的形式发送json字符串 步骤: 1.url .parameters 2.创建httpClient对象 3.创建HttpPost对象 4.为post对象设置参数 5 ...
- 【PostMan】1、Postman 发送json格式请求
Postman 是一个用来测试Web API的Chrome 外挂软件,可由google store 免费取得并安装于Chrome里,对于有在开发Web API的开发者相当有用,省掉不少写测试页面呼叫的 ...
- HttpClient通过Post方式发送Json数据
服务器用的是Springmvc,接口内容: @ResponseBody @RequestMapping(value="/order",method=RequestMethod.PO ...
- Java 通过HttpClient Post方式提交json请求
package com.sinosoft.ap.harmfullibrary.util; /** * 发送post请求 */import net.sf.json.JSONObject; import ...
- springboot使用RestTemplate以post方式发送json字符串参数(以向钉钉机器人发送消息为例)
使用springboot之前,我们发送http消息是这么实现的 我们用了一个过时的类,虽然感觉有些不爽,但是出于一些原因,一直也没有做处理,最近公司项目框架改为了springboot,springbo ...
随机推荐
- 1分钟了解MyISAM与InnoDB的索引差异
版权声明:本文为博主原创文章,未经博主同意不得转载. https://blog.csdn.net/z50L2O08e2u4afToR9A/article/details/82111747 <数据 ...
- 近5年常考Java面试题及答案整理(二)
上一篇:近5年常考Java面试题及答案整理(一) 31.String s = new String("xyz");创建了几个字符串对象? 答:两个对象,一个是静态区的"x ...
- spark on yarn 无法提交任务问题
java.lang.NoClassDefFoundError: com/sun/jersey/api/client/config/ClientConfig spark任务提交出错. 原因: spark ...
- 架构师如何借鉴他人经验快速成长? | 2018GIAC上海站日程上线!
随着网络技术的迅猛发展,越来越多的企业需要紧跟技术发展潮流以应对层出不穷的业务场景变化.如今多“语言”开发百花齐放,选择何种语言才能在合适的场景中发挥最大价值?互联网业务架构经过了长年的发展,已然朝着 ...
- 不存在具有键“test”的“IEnumerable<SelectListItem>”类型的 ViewData 项。
x 很简单的一个问题,有时候提示语已经写得很清楚了, 但是自己那时候就是"鬼迷心窍"了吧··· 解决方案 public PartialViewResult Edit() { vie ...
- windows查看注册表
首先win+r打开程序搜索框 输入regedit 然后编辑==>查找
- POJ 3764 - The xor-longest Path - [DFS+字典树变形]
题目链接:http://poj.org/problem?id=3764 Time Limit: 2000MS Memory Limit: 65536K Description In an edge-w ...
- CSS3 transform 属性
CSS3 transform 属性 语法: transform: none|transform-functions; 值 描述 none 定义不进行转换. matrix(n,n,n,n,n,n) 定义 ...
- python字符串常用方法
#1.strip()去掉空格(字符串首.尾空格).lstrip()去掉左侧空格.rstrip()去掉右侧空格print(' abc '.lstrip())#>>abcprint(' abc ...
- zabbix客户端自动注册
1. 概述 上一篇内容<zabbix自动发现配置>,大概内容是zabbix server去扫描一个网段,把在线的主机添加到Host列表中.我们本篇内容与上篇相反,这次是Active age ...