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 ...
随机推荐
- Git常见报错及解决方案
报错一: You have not concluded your merge (MERGE_HEAD exists). Please, commit your changes before you c ...
- H3C S5120-52P-WiNet交换机配置
配置console口登录验证密码 <H3C>system-view [H3C]user-interface aux 0 [H3C-ui-aux0]authentication-mode p ...
- [Optimization] Greedy method
Given two sequences of letters A and B, find if B is a subsequence of A in thesense that one can del ...
- [JS] ECMAScript 6 - Array : compare with c#
扩展运算符(spread) 先复习下 rest 参数. (1) argument模式,但不够好. // https://blog.csdn.net/weixin_39723544/article/de ...
- [React] 08 - Tutorial: evolution of code-behind
有了七篇基础学习,了解相关的知识体系,之后便是系统地再来一次. [React] 01 - Intro: javaScript library for building user interfaces ...
- 【Docker】基本命令
1.进入容器交互状态 docker exec -ti xxxx /bin/bash 2.查询镜像 docker images 3.查询容器 docker ps
- js给原型增加新属性和方法
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- 【.NetCore学习】ubuntu16.04 搭建.net core mvc api 运行环境
查看linux内核版本 uname -a 打印结果 python@ubuntu:~$ uname -a Linux ubuntu 4.4.0-31-generic #50-Ubuntu SMP Wed ...
- 使用LevelListDrawable实现Html.fromHtml多张图片显示
stackoverflow网站果然强大,帮了我不少忙! http://stackoverflow.com/questions/16179285/html-imagegetter-textview 首先 ...
- [IOI 2000]POJ 1160 Post Office
Post Office Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 22278 Accepted: 12034 Descrip ...