使用场景
每个商户信息不一样,字段且不一样,商户信息统一用json格式保存至数据库;商户信息也可以文件内容,所以有了如下的实现。
实现步骤
文件内容转成字符串
FileInputStream inputStream
= new FileInputStream("E:\\dolphin\\pays\\apiclient_cert.p12");
ByteArrayOutputStream byteArrayOutputStream
= new ByteArrayOutputStream();
int len
;
while ((len
= inputStream
.read()) != -1) {
byteArrayOutputStream
.write(len
);
}
inputStream
.close();
byte[] fileData
= byteArrayOutputStream
.toByteArray();
byteArrayOutputStream
.close();
fileStr
= new String(fileData
, StandardCharsets
.ISO_8859_1
);
作为字段存入JSON
@Test
public void addTest() {
HttpMerchantIdentifyAddRequest request
= new HttpMerchantIdentifyAddRequest();
request
.setAccountNo("testMerchantIndexCodePms");
request
.setPayType("weChatPay");
request
.setMerchantIdentyName("测试");
request
.setExtendInfo("string");
Map
<String, String> data
= new HashMap<>();
data
.put("weChatAppId", "123");
data
.put("weChatMchId", "1222");
data
.put("weChatMchKey", "123354");
data
.put("certFileData", fileStr
);
request
.setContent(JsonUtil
.toJson(data
));
sendPost("http://10.19.132.178:8080/pays/api/merchantIdentify/add/V1", JsonUtil
.toJson(request
));
}
数据库保存
将content字段类型设置为文本型
create table tb_merchant_identify
(
id
varchar(64) not null
,
merchant_identify_name
varchar(48) ,
pay_type
varchar(48) not null
,
account_no
varchar(64) not null
,
content text
,
create_time timestamp not null
,
update_time timestamp not null
,
extend
varchar(48) ,
constraint pk_tb_merchant_identify primary key
(id
)
);
文件取出使用
FileOutputStream outputStream
= new FileOutputStream("E:\\dolphin\\pays\\temp.p12");
outputStream
.write(fileStr
.getBytes(StandardCharsets
.ISO_8859_1
));
outputStream
.flush();
outputStream
.close();
InputStream inputStream
= new ByteArrayInputStream(certFileData
.getBytes(StandardCharsets
.ISO_8859_1
));
注意:编码要用 StandardCharsets.ISO_8859_1 为单字节编码,用双字节内容会被改变,导致文件内容不一致。