日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

bson实践

發布時間:2024/3/24 编程问答 32 豆豆
生活随笔 收集整理的這篇文章主要介紹了 bson实践 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

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數據需要解析,這里注意用的請求模式不一樣

以上僅僅是小弟的看法,有什么見解有待商榷…

總結

以上是生活随笔為你收集整理的bson实践的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。