前言: 

  项目调用第三方接口时,通常是用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指南练习_映射

    源地址 https://tour.go-zh.org/moretypes/23 一.题目描述 实现 WordCount.它应当返回一个映射,其中包含字符串 s 中每个“单词”的个数.函数 wc.Tes ...

  2. windows 注册表讲解

    注册表存储结构: 整个注册表内容主要由项(键).值(键值)构成.(通过regedit命令打开注册表) 5个根键: HKEY_CLASSES_ROOT    (缩写HKCR) HKEY_CURRENT_ ...

  3. [Object Tracking] MeanShift

    使用Opencv中均值漂移meanShift跟踪移动目标 Opencv均值漂移pyrMeanShiftFiltering彩色图像分割流程剖析 Opencv目标跟踪—CamShift算法 MeanShi ...

  4. [PHP] 02 - Namespace & Class

    两个比较大的话题,独立成本篇. 面向对象编程 一.命名空间 PHP 命名空间可以解决以下两类问题: 用户编写的代码与PHP内部的类/函数/常量或第三方类/函数/常量之间的名字冲突. 为很长的标识符名称 ...

  5. ThinkingInJava 学习 之 0000002 操作符

    1. 更简单的打印语句 2. 使用Java操作符 3. 优先级(单目乘除位关系,逻辑三目后赋值) 4. 赋值 1. 方法调用中的别名问题 5. 算术操作符 6. 自动递增和递减 7. 关系操作符 1. ...

  6. 4. Oracle数据库用户管理备份与恢复

    一. Oracle用户管理备份介绍 Oracle物理备份核心就是将物理文件拷贝一份副本:存放在磁盘上.物理文件指的是:数据文件,控制文件,日志文件,参数文件等等. 根据数据库状态而分:备份可分为热备份 ...

  7. Context namespace element 'component-scan' and its parser class [org.springframework.context.annotation.ComponentScanBeanDefinitionParser] are only available on JDK 1.5 and higher

    异常信息如下: 错误: Unexpected exception parsing XML document from class path resource [spring/applicationCo ...

  8. Markdown 引用

    Markdown 使用 > 来标记区块引用,语法及效果如下: > 这是第一级引用 > > > 这是第二级引用 > > 现在回到第一级引用 > > ...

  9. [Android] 基于 Linux 命令行构建 Android 应用(七):自动化构建

    本章将演示如何基于 Linux 命令行构建 Android 应用,在开始本章之前,希望你已经阅读之前几章内容. 本文环境为 RHEL Sandiego 32-bits,要基于 Linux CLI 构建 ...

  10. connect()返回SOCKET_ERROR不一定就是连接失败

    connect()用于建立与指定socket的连接. 头文件: #include <sys/socket.h> 函数原型: int connect(int s, const struct ...