前言: 

  项目调用第三方接口时,通常是用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报文请求的更多相关文章

  1. java 模拟http请求,通过流(stream)的方式,发送json数据和文件

    发送端: /** * 以流的方式 * 发送文件和json对象 * * @return */ public static String doPostFileStreamAndJsonObj(String ...

  2. java使用POST发送soap报文请求webservice返回500错误解析

    本文使用JAX-WS2.2编译webservice,并使用HttpUrlConnection的POST方式对wsdl发送soap报文进行请求返回数据, 对错误Server returned HTTP ...

  3. volley用法之 以post方式发送 json 参数

    需求是这样 我们需要发送一个post请求向服务器要参数.要求是发送的post参数也要是json格式. 简单一点的是这样的: 如果要发送的是这样简单的json格式,我们可以简单的使用map来实现: Re ...

  4. ABAP接口之Http发送json报文

    abap 调用http 发送 json 测试函数 SE11创建结构:zsmlscpnotice SE37创建函数:zqb_test_http_fuc1 FUNCTION zqb_test_http_f ...

  5. HttPclient 以post方式发送json

    使用HttpClient 以POST的形式发送json字符串 步骤: 1.url .parameters 2.创建httpClient对象 3.创建HttpPost对象 4.为post对象设置参数 5 ...

  6. 【PostMan】1、Postman 发送json格式请求

    Postman 是一个用来测试Web API的Chrome 外挂软件,可由google store 免费取得并安装于Chrome里,对于有在开发Web API的开发者相当有用,省掉不少写测试页面呼叫的 ...

  7. HttpClient通过Post方式发送Json数据

    服务器用的是Springmvc,接口内容: @ResponseBody @RequestMapping(value="/order",method=RequestMethod.PO ...

  8. Java 通过HttpClient Post方式提交json请求

    package com.sinosoft.ap.harmfullibrary.util; /** * 发送post请求 */import net.sf.json.JSONObject; import ...

  9. springboot使用RestTemplate以post方式发送json字符串参数(以向钉钉机器人发送消息为例)

    使用springboot之前,我们发送http消息是这么实现的 我们用了一个过时的类,虽然感觉有些不爽,但是出于一些原因,一直也没有做处理,最近公司项目框架改为了springboot,springbo ...

随机推荐

  1. Go语言_range(范围)理解

    一.Go语言中的range Go 语言中 range 关键字用于 for循环中迭代数组(array).切片(slice).链表(channel)或集合(map)的元素: 在数组和切片中它返回元素的索引 ...

  2. Mysql系列七:分库分表技术难题之分布式全局唯一id解决方案

    一.前言 在前面的文章Mysql系列四:数据库分库分表基础理论中,已经说过分库分表需要应对的技术难题有如下几个: 1. 分布式全局唯一id 2. 分片规则和策略 3. 跨分片技术问题 4. 跨分片事物 ...

  3. [Artoolkit] Android Sample of nftSimple

    结合:[Artoolkit] ARToolKit's SDK Structure on Android 重难点:aRBaseLib/, nftSimple/, libcpufeatures.a aRB ...

  4. HTTPS与证书

    HTTPS(Secure Hypertext Transfer Protocol)安全超文本传输协议它是一个安全通信通道,它基于HTTP开发,用于在客户计算机和服务器之间交换信息.它使用安全套接字层( ...

  5. 秒杀应用的MySQL数据库优化

    关于秒杀 随着双11活动的不断发展,小米饥饿营销模式的兴起,“秒杀”已经成为一个热点词汇.在一些活动中,热销商品会以惊人的速度售罄,比如最近本人在抢购美图M4手机,12点开卖,1分钟之内就被售罄. 秒 ...

  6. 【mysql】---php链接数据库---【巷子】

    一.创建public文件 <?php //第一件事情连接数据库 header("content-type:text/html;charset=utf8"); //服务器地址 ...

  7. 使用 PREPARE 的几个注意点

    简单的用set或者declare语句定义变量,然后直接作为sql的表名是不行的,mysql会把变量名当作表名.在其他的sql数据库中也是如此,mssql的解决方法是将整条sql语句作为变量,其中穿插变 ...

  8. db2 backup export

    备份命令: db2 backup db test to /db2data/ 监控备份进度: db2 list utilities show detail <-进度 检测备份文件的有效性: db2 ...

  9. 洛谷P3952 时间复杂度【字符串】【模拟】

    题目描述 小明正在学习一种新的编程语言 A++,刚学会循环语句的他激动地写了好多程序并 给出了他自己算出的时间复杂度,可他的编程老师实在不想一个一个检查小明的程序, 于是你的机会来啦!下面请你编写程序 ...

  10. CMake error with move_base_msgs问题解决

    错误 CMake Error at /opt/ros/groovy/share/catkin/cmake/catkinConfig.cmake: (find_package): Could not f ...