笔记:Jersey REST 传输格式
通常REST接口会以XML或JSON作为主要传输格式,同时 Jersey 也支持其他的数据格式,比如基本类型、文件、流等格式。
- 基本类型
Java的基本类型又叫原生类型,包括4种整数(byte、short、int、long)、2种浮点类型(float、double)、Unicode编码的字符(char)和布尔类型(boolean),Jersey 支持全部的基本类型,还支持与之相关的引用类型,示例代码如下:
- REST 服务代码
@POST
@Path("b")
public String postBytes(final byte[] bs) {
for (final byte b : bs) {
System.out.print(Integer.toHexString(b) + " ");
}
return "byte[]:" + new String(bs);
}
- 单元测试
@Test
public void postBytesTest() {
final String message = "TEST STRING";
final Invocation.Builder request = target.path("demos").path("b").request();
final Response response = request.post(Entity.entity(message, MediaType.TEXT_PLAIN_TYPE), Response.class);
String result = response.readEntity(String.class);
System.out.println("result:" + result);
Assert.assertTrue("字符串不匹配", result.equals("byte[]:" + message));
}
- 文件类型
Jersey 支持传输 File 类型的数据,以方便客户端直接传递File类实例给服务端,文件类型的请求,默认使用的媒体类型是 Content-Type:text/html,示例代码如下:
- REST服务代码
@POST
@Path("file")
public String uploadFile(final File file) {
StringBuilder sb = new StringBuilder(1024000 * 5);
try (BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(file))) {
byte[] buff = new byte[102400];
int readCount;
String dir = System.getProperty("user.dir");
File outputFile = new File(dir + "\\updateFile");
try (BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(outputFile))) {
do {
readCount = bufferedInputStream.read(buff, 0, buff.length);
if (readCount > 0) {
bufferedOutputStream.write(buff, 0, readCount);
}
} while (readCount > 0);
}
return "ok";
} catch (Exception ex) {
ex.printStackTrace();
return "";
}
}
- 单元测试
@Test
public void PostFileTest() {
URL resource = getClass().getClassLoader().getResource("TortoiseGit-2.3.0.0-64bit.msi");
File file = new File(resource.getFile());
Invocation.Builder builder = target.path("demos").path("file").request();
Response response = builder.post(Entity.entity(file, MediaType.TEXT_HTML_TYPE));
if (response.getStatus() == 200) {
String result = response.readEntity(String.class);
System.out.println(result);
} else {
System.out.println("response status=" + response.getStatus() + "\tmessage=" + response.getStatusInfo());
}
}
- 字节流和字符流类型
Jersey 支持Java的两大读写模式,即字节流和字符流
- 字节流:
- REST服务代码
@POST
@Path("fileInputStream")
public String uploadFileByInputStream(final InputStream inputStream) {
StringBuilder sb = new StringBuilder(1024000 * 5);
try (BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream)) {
byte[] buff = new byte[102400];
int readCount;
String dir = System.getProperty("user.dir");
File outputFile = new File(dir + "\\updateFile");
try (BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(outputFile))) {
do {
readCount = bufferedInputStream.read(buff, 0, buff.length);
if (readCount > 0) {
bufferedOutputStream.write(buff, 0, readCount);
}
} while (readCount > 0);
}
return "ok";
} catch (Exception ex) {
ex.printStackTrace();
return "";
}
}
- 单元测试
@Test
public void PostFileByInputStreamTest() {
InputStream inputStream = null;
try {
inputStream = getClass().getClassLoader().getResource("TortoiseGit-2.3.0.0-64bit.msi").openStream();
Invocation.Builder builder = target.path("demos").path("fileInputStream").request();
Response response = builder.post(Entity.entity(inputStream, MediaType.TEXT_PLAIN_TYPE));
if (response.getStatus() == 200) {
String result = response.readEntity(String.class);
System.out.println(result);
} else {
System.out.println("response status=" + response.getStatus() + "\tmessage=" + response.getStatusInfo());
}
} catch (IOException e) {
e.printStackTrace();
}
}
- 字符流:
- REST服务代码
@POST
@Path("fileReader")
public String uploadFileByReader(final Reader reader) {
StringBuilder sb = new StringBuilder(1024000 * 5);
try (BufferedReader bufferedReader = new BufferedReader(reader)) {
byte[] buff = new byte[102400];
String readLine;
String dir = System.getProperty("user.dir");
File outputFile = new File(dir + "\\updateFile.xml");
try (BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(outputFile))) {
do {
readLine = bufferedReader.readLine();
if (readLine != null) {
bufferedWriter.write(readLine);
bufferedWriter.newLine();
}
} while (readLine != null);
}
return "ok";
} catch (Exception ex) {
ex.printStackTrace();
return "";
}
}
- 单元测试
@Test
public void PostFileByReaderTest() {
InputStream inputStream = null;
try {
inputStream = getClass().getClassLoader().getResource("POM.xml").openStream();
Invocation.Builder builder = target.path("demos").path("fileReader").request();
Response response = builder.post(Entity.entity(inputStream, MediaType.TEXT_PLAIN_TYPE));
String result = response.readEntity(String.class);
System.out.println(result);
} catch (IOException e) {
e.printStackTrace();
}
}
笔记:Jersey REST 传输格式的更多相关文章
- 笔记:Jersey REST 传输格式-JSON
JSON 类型已经成为Ajax技术中数据传输的实际标准,Jersey 提供了多种处理JSON数据的包和解析方式,下表展示了JSON包和解析方式: 解析方式\JSON支持包 MOXy JSON-P Ja ...
- 笔记:Jersey REST 传输格式-XML
XML类型是使用最广泛的数据类型,Jersey 对XML类型的数据处理,支持Java领域的两大标准,即JAXP(Java API for XML Processing,JSR-206)和JAXB(Ja ...
- 图解 TCP/IP 第六章 TCP与UDP 笔记6.1 传输层的作用
图解 TCP/IP 第六章 TCP与UDP 笔记6.1 传输层的作用 传输层必须指出这个具体的程序,为了实现这一功能,使用端口号这样一种识别码.根据端口号,就可以识别在传输层上一层的应用程 ...
- QT断点续传(原理:需要在HTTP请求的header中添加Rang节,告诉服务器从文件的那个位置开始传输.格式为bytes 开始传输的位置)
//功能: 根据一个URL地址将数据保存到指定路径下,支持断点续传//参数: url --需要访问的URL地址// SavePath -- ...
- 一个基于JRTPLIB的轻量级RTSP客户端(myRTSPClient)——实现篇:(八)RTP音视频传输解析层之MPA传输格式
一.MPEG RTP音频传输 相较H264的RTP传输格式,MPEGE音频传输格式则简单许多. 每一包MPEG音频RTP包都前缀一个4字节的Header,如下图(RFC2550) “MBZ”必须为0( ...
- 一个基于JRTPLIB的轻量级RTSP客户端(myRTSPClient)——实现篇:(七)RTP音视频传输解析层之H264传输格式
一.H264传输封包格式的2个概念 (1)组包模式(Packetization Modes) RFC3984中定义了3种组包模式:单NALU模式(Single Nal Unit Mode).非交错模式 ...
- 在同一个项目中灵活运用application/json 和application/x-www-form-urlencoded 两种传输格式(配合axios,同时配置loading)
'use strict' import axios from 'axios' // import qs from 'qs' import { Notification} from 'element-u ...
- Fortran学习笔记:01 基本格式与变量声明
Fortran学习笔记目录 01 基本格式与变量声明 格式 固定格式(Fixed Format):Fortran77 程序需要满足一种特定的格式要求,具体形式参考教材 自由格式(Free Format ...
- HTTP的FormData和Payload的传输格式
FormData和Payload是浏览器传输给接口的两种格式,这两种方式浏览器是通过Content-Type来进行区分的(了解Content-Type),如果是 application/x-www-f ...
随机推荐
- SAS︱操作语句(if、do、select、retain、array)、宏语言、统计量、运算符号
每每以为攀得众山小,可.每每又切实来到起点,大牛们,缓缓脚步来俺笔记葩分享一下吧,please~ --------------------------- SAS中的一些常见的符号.运算符是一种符号①比 ...
- android的Findbugs问题整理
1. 对字符串不相等的判断 错误 if (chapterInfo.getPayMode() != String.valueOf(com.shuqi.base.common.Constant.PAYMO ...
- 好用的Markdown编辑器汇总
Markdown 是一种简单的.轻量级的标记语法.用户可以使用诸如 * # 等简单的标记符号以最小的输入代价生成极富表现力的文档. Markdown具有很多优点: 写作中添加简单符号即完成排版,所见即 ...
- HI3531网络tftp、nfs加载
ifconfig eth0 hw ether 00:00:23:34:45:66; ifconfig eth0 192.168.1.10 netmask 255.255.255.0; route a ...
- Flex中一些属性总结
Flex中一些属性总结 1.buttonMode = "true" 鼠标变成手形 2.useHandCursor = "true" 鼠标变成手形
- SUSE(Linux操作系统)
suse linux 即 SUSE (Linux操作系统) . SUSE(发音为/zuz?/),发音的音频文件.SUSE Linux 原来是德国的 SuSE Linux AG公司发行维护的Linux发 ...
- TypeError: Error #1034: 强制转换类型失败:无法将 mx.controls::DataGrid@9a7c0a1 转换为 spark.core.IViewport。
1.错误描述 TypeError: Error #1034: 强制转换类型失败:无法将 mx.controls::DataGrid@9aa90a1 转换为 spark.core.IViewport. ...
- TypeError: Error #1006: value 不是函数。
1.错误原因 TypeError: Error #1006: value 不是函数. at BasicChart/dataFunc()[E:\Flash Builder\Map\src\BasicCh ...
- NCBI下载sra数据(新)
今天要上NCBI下载sra数据发现没有下载的链接,网上查发现都是老的方法,NCBI页面已经变更,于是看了NCBI的help,并且记录下来新版的sra数据下载方法,要用NCBI的工具SRA Tool ...
- TOJ 4120 Zombies VS Plants
链接:http://acm.tju.edu.cn/toj/showp4120.html 4120. Zombies VS Plants Time Limit: 1.0 Seconds Memo ...