SpringBoot基础系列:优雅处理byte[]
- 使用@RequestBody接收byte[];- 通过字节流OutputStream生成二进制文件;- Postman构造请求时,在Body体中使用二进制形式发送byte[];- RestTemplate携带byte[]时使用ByteArrayResource作为HttpEntity类型。
1 byte[]
字节数组。二进制文件形式存储数据。
byte:字节。Java基础数据类型之一。
取值范围:[
−
2
7
-2^7
−27,
2
7
2^7
27-1]=[-128, 127]
默认值:0
字节数组即应用字节传输数据。
字节流基于字节数组传输数据。
使用字节数组传输数据传输效率更高,序列化码流小,降低时延。
适用于系统内部数据传输。如后台接口之间数据传输。
2 传输byte[]
2.1 接收byte[]
使用@RequestBody接收byte[]
package com.monkey.tutorial.api;
import com.monkey.tutorial.common.response.Response;
import com.monkey.tutorial.modules.test.vo.TestInputVO;
import com.monkey.tutorial.modules.test.vo.TestOutputVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.websocket.server.PathParam;
/**
* 测试API
*
* @author xindaqi
* @since 2021-05-08 23:03:50
*/
@RestController
@RequestMapping("/api/v1")
public class TestApi {
private static final Logger logger = LoggerFactory.getLogger(TestApi.class);
@PostMapping("/post/bytes")
public Response<String> postBytesInBody(@RequestBody byte[] bytes) {
String str = new String(bytes);
System.out.println(">>>>>>>Bytes:" + str);
return Response.success(str);
}
}
2.2 生成二进制文件
生成字节流文件,作为请求体。
package com.monkey.java_study.io;
import com.monkey.java_study.common.constant.DigitalConstant;
import com.monkey.java_study.common.constant.FilePathConstant;
import java.io.*;
import java.util.Properties;
import java.util.logging.Logger;
/**
* Input/OutputStream测试.
*
* @author xindaqi
* @date 2021-06-29 17:54
*/
public class InOutStreamTest {
private static final Logger logger = Logger.getLogger("InOutStreamTest");
/**
* 复制源文件内容到新文件.
*
* @param filePath 源文件路径
* @param fileName 新文件名称,如tests.txt
*/
private static void copyFile(String filePath, String fileName) {
try(InputStream ins = ClassLoader.getSystemClassLoader().getResourceAsStream(FilePathConstant.LOG_4_J_CONFIG_PATH);
OutputStream ots = new FileOutputStream("D:"+ File.separator + "workfile" + File.separator + "java-file-save" + File.separator + fileName)) {
int len = ins.available();
logger.info("file length: " + len);
/**
* 1MB = 1024KBytes=1024*1024Bytes
* 文件小于1M
*/
if(len <= DigitalConstant.MB_UNIT_TO_BYTE) {
byte[] bytes = new byte[len];
ins.read(bytes);
ots.write(bytes);
} else {
int byteCount = 0;
byte[] bytes = new byte[DigitalConstant.MB_UNIT_TO_BYTE];
while((byteCount = ins.read(bytes)) != DigitalConstant.NEGATIVE_ONE) {
ots.write(bytes, 0, byteCount);
}
}
} catch(FileNotFoundException e) {
throw new RuntimeException(e);
} catch(Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) throws IOException {
InOutStreamTest.copyFile(FilePathConstant.LOG_4_J_CONFIG_PATH, "test");
}
}
生成的文件:
2.3 测试byte[]传输
使用请求体body接收二进制文件(byte[])。
Postman构造请求如下:
3 使用RestTemplate发送byte[]
3.1 构建请求
通过RestTemplate请求byte[]参数的接口,通过ByteArrayResource构建字节数组资源。
package com.monkey.tutorial.api;
import com.monkey.tutorial.common.response.Response;
import com.monkey.tutorial.common.util.FileProcessUtil;
import com.monkey.tutorial.modules.redis.vo.UserVO;
import com.monkey.tutorial.modules.user.vo.BaseUserVO;
import org.springframework.core.io.ByteArrayResource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import javax.websocket.server.PathParam;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.util.*;
/**
* RestTemplate测试接口.
*
* @author xindaqi
* @date 2021-08-17 22:34
*/
@RestController
@RequestMapping("/api/v1/restTemplate")
@SuppressWarnings("unchecked")
public class RestTemplateApi {
@Resource
RestTemplate restTemplate;
@PostMapping("/getBytes")
public Response<String> getBytesFromApi() {
HttpHeaders httpHeaders = new HttpHeaders();
String url = "http://localhost:9121/api/v1/post/bytes";
String str = "Hello world!";
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
os.write(str.getBytes());
byte[] bytes = os.toByteArray();
HttpEntity<ByteArrayResource> httpEntity = new HttpEntity<>(new ByteArrayResource(bytes), httpHeaders);
ResponseEntity<Response> response = restTemplate.exchange(url, HttpMethod.POST, httpEntity, Response.class);
return response.getBody();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
3.2 接口测试
4 小结
- 使用@RequestBody接收byte[];
- 通过字节流OutputStream生成二进制文件;
- Postman构造请求时,在Body体中使用二进制形式发送byte[];
- RestTemplate携带byte[]时使用ByteArrayResource作为HttpEntity类型。
更多推荐
所有评论(0)