bson实践
在工作中遇到的bson的数据局格式,简单记录一下bson数据的用法
1.BSON(/ˈbiːsən/)是一种计算机数据交换格式,主要被用作MongoDB数据库中的数据存储和网络传输格式。它是一种二进制表示形式,能用来表示简单数据结构、关联数组(MongoDB中称为“对象”或“文档”)以及MongoDB中的各种数据类型。BSON之名缘于JSON,含义为Binary JSON(二进制JSON)。
二.封装bson
依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.6</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.6</version>
</dependency>
<dependency>
<groupId>org.mongodb</groupId>
<artifactId>bson</artifactId>
<version>3.8.2</version>
</dependency>
<dependency>
<groupId>de.undercouch</groupId>
<artifactId>bson4jackson</artifactId>
<version>2.9.2</version>
</dependency>
话不多说直接上代码
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectMapper mapper = new ObjectMapper(new BsonFactory());
mapper.writeValue(baos,map1);
byte[] bs = baos.toByteArray();
//写入文件中
FileWriter writer = new FileWriter("/temp/lishanzhaung.bson");
writer.write(baos.toByteArray(), 0, baos.toByteArray().length); //对数据的一个简单保存
//访问接口开始
String url="你的url";
HashMap<String, byte[]> map = new HashMap<>();
map.put("data",bs);
Post post = new Post();
String post2 = post.post(url, map);
简单说明一下,map1是我分装的数据(可以用对象或者其他),因为客户接口需要的是bson数据形式,这样就实现了对map数据的转换
以上有两点写入本地文件的代码还有post的代码
//post请求代码
package nc.bs.cmet.nobidding.purchase;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Random;
import javax.net.ssl.SSLException;
public class Post {
public static String post(String url,HashMap<String, byte[]> fileMap) throws Exception {
int CONNECT_TIME_OUT = 30000;
int READ_OUT_TIME = 50000;
String boundaryString = getBoundary();
HttpURLConnection conne;
URL url1 = new URL(url);
conne = (HttpURLConnection) url1.openConnection();
conne.setDoOutput(true);
conne.setUseCaches(false);
conne.setRequestMethod("POST");
conne.setConnectTimeout(CONNECT_TIME_OUT);
conne.setReadTimeout(READ_OUT_TIME);
conne.setRequestProperty("accept", "*/*");
conne.setRequestProperty("Charset", "UTF-8");
conne.setRequestProperty("Accept-Charset", "UTF-8");
conne.setRequestProperty("Content-Type", "multipart/form-data;charset=utf-8; boundary=" + boundaryString);
conne.setRequestProperty("connection", "Keep-Alive");
conne.setRequestProperty("user-agent", "Mozilla/4.0 (compatible;MSIE 6.0;Windows NT 5.1;SV1)");
DataOutputStream obos = new DataOutputStream(conne.getOutputStream());
if(fileMap != null && fileMap.size() > 0){
Iterator fileIter = fileMap.entrySet().iterator();
while(fileIter.hasNext()){
Map.Entry<String, byte[]> fileEntry = (Map.Entry<String, byte[]>) fileIter.next();
obos.writeBytes("--" + boundaryString + "\r\n");
obos.writeBytes("Content-Disposition: form-data; name=\"" + fileEntry.getKey()
+ "\"; filename=\"" + encode(" ") + "\"\r\n");
obos.writeBytes("\r\n");
obos.write(fileEntry.getValue());
obos.writeBytes("\r\n");
}
}
obos.writeBytes("--" + boundaryString + "--" + "\r\n");
obos.writeBytes("\r\n");
obos.flush();
obos.close();
InputStream ins = null;
int code = conne.getResponseCode();
try{
if(code == 200){
ins = conne.getInputStream();
}else{
ins = conne.getErrorStream();
}
}catch (SSLException e){
e.printStackTrace();
return "";
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buff = new byte[4096];
int len;
while((len = ins.read(buff)) != -1){
baos.write(buff, 0, len);
}
byte[] bytes = baos.toByteArray();
ins.close();
String str = null;
try {
str = new String(bytes,"UTF-8");
new String(bytes);
}catch (Exception e){
e.printStackTrace();
}
/* Object unserializeObj = VO2Byte.unserializeObj(bytes);
String str = String.valueOf(unserializeObj);*/
return str;
}
public static final String byte2hex(byte b[]) {
if (b == null) {
throw new IllegalArgumentException("Argument b ( byte array ) is null! ");
}
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = Integer.toHexString(b[n] & 0xff);
if (stmp.length() == 1) {
hs = hs + "0" + stmp;
} else {
hs = hs + stmp;
}
}
return hs.toUpperCase();
}
private static String getBoundary() {
StringBuilder sb = new StringBuilder();
Random random = new Random();
for(int i = 0; i < 32; ++i) { sb.append("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-".charAt(random.nextInt("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_".length())));
}
return sb.toString();
}
private static String encode(String value) throws Exception{
return URLEncoder.encode(value, "UTF-8");
}
}
写入本地文件
依赖
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.0.12</version>
</dependency>
<dependency>
<groupId>org.apache.commons.io</groupId>
<artifactId>commonsIO</artifactId>
<version>2.5.0</version>
<type>pom</type>
</dependency>
import java.io.File;
import cn.hutool.core.io.file.FileWriter;
import nc.vo.pubapp.AppContext;
public class FileWriterUtil {
public void Log(String msg) {
try {
String sysDate = AppContext.getInstance().getServerTime().getDate().toString();// 获取当前系统时间
String msgA = sysDate + ":" + msg + ";";
//路径
File fDir = new File(File.separator); // File.separator表示根目录,比如现在就表示在D盘下。
String strFile = "temp" + File.separator + "loglishanzhuang.txt"; // 这个就是绝对路径
File f = new File(fDir, strFile);
//创建路径
FileWriter writer = new FileWriter(f.getPath());
// FileWriter writer = new FileWriter("C:\\temp\\log.txt");
byte[] bytes = msgA.getBytes();
writer.write(bytes, 0, bytes.length, true); // 写入到文件
} catch (Exception e) {
e.printStackTrace();
}
}
}
三 解析bson数据
map.put("v","1.1");
map.put("data",jsonObject);
String url = "你的url";
try {
byte[] dataByte = null;
org.apache.http.client.HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
UrlEncodedFormEntity encodedFormEntity = new UrlEncodedFormEntity(setHttpParams(map), "UTF-8");
httpPost.setEntity(encodedFormEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
// 获取返回的数据
HttpEntity httpEntity = httpResponse.getEntity();
if (httpEntity != null) {
byte[] responseBytes = getData(httpEntity);
dataByte = responseBytes;
ByteArrayInputStream bais =null;
bais = new ByteArrayInputStream(responseBytes);
ObjectMapper mapper = new ObjectMapper(new BsonFactory());
Map<String,Object> object =mapper.readValue(bais, Map.class);
JSONObject jsonObjectResult = JSONObject.fromObject(object);
}
这个是用bson数据调用别人接口.返回的是bson数据需要解析,这里注意用的请求模式不一样
以上仅仅是小弟的看法,有什么见解有待商榷…