Java發(fā)送報(bào)文與接收?qǐng)?bào)文的實(shí)例代碼
報(bào)文(message)是網(wǎng)絡(luò)中交換與傳輸?shù)臄?shù)據(jù)單元,即站點(diǎn)一次性要發(fā)送的數(shù)據(jù)塊。報(bào)文包含了將要發(fā)送的完整的數(shù)據(jù)信息,其長(zhǎng)短很不一致,長(zhǎng)度不限且可變。
個(gè)人理解:從客戶端把字符串寫(xiě)入字節(jié)數(shù)組流中傳達(dá)至服務(wù)端,但是此字符串是XML格式的,然后到了服務(wù)端,使用字節(jié)數(shù)組進(jìn)行獲取該字符串,再獲取該字符串的document對(duì)象(因?yàn)樽址莤ml格式的),然后解析獲取數(shù)據(jù)即可。
發(fā)送報(bào)文
先創(chuàng)建生成報(bào)文的方法,添加了xml數(shù)據(jù)
/** * @desc 生成xml報(bào)文且轉(zhuǎn)換為字符串 * @return */ public String xmlToString() { StringBuffer sendStr = new StringBuffer(); // 以下為添加的xml信息 sendStr.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>"); sendStr.append("<request_data>"); sendStr.append("<request_token>BCDBCD</request_token>"); sendStr.append("<request_cardNum>62284801912705</request_cardNum>"); sendStr.append("<request_name>張飛</request_name>"); sendStr.append("<request_pass>123123</request_pass>"); sendStr.append("<request_time>"+new Dates().CurrentYMDHSMTime()+"</request_time>"); sendStr.append("<monery_count>200.00</monery_count>"); sendStr.append("<shop_name>吉野家</shop_name>"); sendStr.append("<shop_id>JYJ</shop_id>"); sendStr.append("<sale_no>"+UUID.randomUUID().toString()+"</sale_no>"); sendStr.append("</request_data>"); // 創(chuàng)建字符串用于返回 String str = sendStr.toString(); return str; }
將報(bào)文xml轉(zhuǎn)為流寫(xiě)入
/** * @desc 將xml轉(zhuǎn)為流寫(xiě)入 * @param servletConnection * @throws IOException */ public void xmlWriteStream(HttpURLConnection servletConnection) throws IOException { // 創(chuàng)建流,寫(xiě)入xml數(shù)據(jù) OutputStream ouput = servletConnection.getOutputStream(); // 調(diào)用方法獲取xml字符串 String str = xmlToString(); System.out.println(str); // 將xml字符串轉(zhuǎn)為btye數(shù)組寫(xiě)入流 ouput.write(str.getBytes("UTF-8")); ouput.flush();// 刷新流 ouput.close();// 關(guān)閉流 }
創(chuàng)建客戶端與服務(wù)端的連接并且設(shè)置發(fā)送報(bào)文的一些屬性
/** * @desc 創(chuàng)建客戶端與服務(wù)端的連接并且設(shè)置發(fā)送報(bào)文的一些屬性 * @return * @throws IOException */ public HttpURLConnection cerateServletUrl() throws IOException { // 服務(wù)端地址 URL uploadServlet = new URL("http://localhost:1023/BaoWenServer/xmlServlet.do"); // 創(chuàng)建連接 HttpURLConnection servletConnection = (HttpURLConnection) uploadServlet.openConnection(); // 設(shè)置連接參數(shù) servletConnection.setRequestMethod("POST"); // 請(qǐng)求類型為post servletConnection.setDoOutput(true); // 是否可讀 servletConnection.setDoInput(true); // 是否可寫(xiě) servletConnection.setAllowUserInteraction(true); // 是否可交互 return servletConnection; }
獲取服務(wù)端反饋回來(lái)的結(jié)果
/** * @desc 獲取服務(wù)端反饋回來(lái)的結(jié)果 * @param servletConnection * @throws IOException */ public void getResponseResult(HttpURLConnection servletConnection) throws IOException { System.out.println("===============**服務(wù)端的返回值**=================="); // 獲取返回的數(shù)據(jù) InputStream inputStream = servletConnection.getInputStream();//獲取反饋回來(lái)的流 //創(chuàng)建一個(gè)緩沖讀取的reader對(duì)象 BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); //創(chuàng)建一個(gè)能夠承接返回來(lái)值得sb StringBuffer sb = new StringBuffer(); //創(chuàng)建一個(gè)能夠臨時(shí)存儲(chǔ)讀取一行信息的變量 String strMessage = ""; //開(kāi)始循環(huán)讀取返回的流信息 while ((strMessage = reader.readLine()) != null) { sb.append(strMessage);//將返回的流的信息逐行的壓如到sb中 } System.out.println("接收返回值:" + sb); }
最后的調(diào)用方法
/** * @throws IOException * @desc 用于調(diào)用方法發(fā)送報(bào)文的方法 */ public void sendMessage() throws IOException { try { System.out.println("=================開(kāi)始發(fā)送報(bào)文================="); // 建立連接 HttpURLConnection servletConnection = cerateServletUrl(); // 寫(xiě)入數(shù)據(jù) xmlWriteStream(servletConnection); // 獲取返回?cái)?shù)據(jù) getResponseResult(servletConnection); } catch (java.net.ConnectException e) { System.out.println("客戶端與服務(wù)端連接異常,請(qǐng)?jiān)俅螄L試"); } }
接收?qǐng)?bào)文
服務(wù)端使用web項(xiàng)目進(jìn)行構(gòu)建
在service中設(shè)置編碼集
request.setCharacterEncoding("utf-8"); response.setCharacterEncoding("utf-8");
獲取客戶端發(fā)送過(guò)來(lái)的報(bào)文
//----------------通過(guò)request.getInputStream()獲取輸入的流---------------------- // 指定每次8kb final int BUFFER_SIZE = 8 * 1024; byte[] buffer = new byte[BUFFER_SIZE]; // 獲取輸出流,與客戶端的輸出流相對(duì)應(yīng) ServletInputStream sis = request.getInputStream(); // System.out.println("sis:"+sis); int length = 0; // 創(chuàng)建字節(jié)輸出流 ByteArrayOutputStream baos = new ByteArrayOutputStream(); do { length = sis.read(buffer); if (length > 0) { // 寫(xiě)入至字節(jié)輸出流 baos.write(buffer, 0, length); } } while (length * 2 == BUFFER_SIZE); // 把字節(jié)輸出流轉(zhuǎn)為字符串,得到客戶端發(fā)送的數(shù)據(jù),即為報(bào)文 String bodyData = new String(baos.toByteArray());
此時(shí)bodyData
就是客戶端發(fā)送來(lái)的報(bào)文數(shù)據(jù):
<?xml version="1.0" encoding="utf-8"?> <request_data> <request_token>BCDBCD</request_token> <request_cardNum>62284801912705</request_cardNum> <request_name>張飛</request_name> <request_pass>123123</request_pass> <request_time>2021年01月25日 14:51:52</request_time> <monery_count>200.00</monery_count> <shop_name>吉野家</shop_name> <shop_id>JYJ</shop_id> <sale_no>fc4c66dc-b54b-4052-89c1-902be7569f18</sale_no> </request_data>
讀該xml可分析數(shù)據(jù):張飛在2021年01月25日 14:51:52在商家id為JYJ的吉野家消費(fèi)了200.00元,本次消費(fèi)的流水單號(hào)為fc4c66dc-b54b-4052-89c1-902be7569f18,使用的卡號(hào)為62284801912705,該卡密碼為123123(未采用加密),且當(dāng)前的標(biāo)識(shí)碼為BCDBCD
解析報(bào)文
客戶端發(fā)送的報(bào)文數(shù)據(jù)為Xml類型,所以直接用Xml的數(shù)據(jù)解析方法解析即可
// 獲取報(bào)文之后,開(kāi)始解析報(bào)文,即為解析Xml //1.初始化jdk中的用來(lái)解析xml的dom工廠 DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); //2:獲得具體的dom解析器 DocumentBuilder db = dbf.newDocumentBuilder(); //3: 解析一個(gè)xml文檔,獲得Document對(duì)象(根結(jié)點(diǎn)) InputSource is = new InputSource(new StringReader(bodyData)); Document document = null; try{ document = db.parse(is);//將流轉(zhuǎn)換成document對(duì)象 }catch(Exception e){ return ; }
獲取完document對(duì)象之后,開(kāi)始解析
//通過(guò)抓取根節(jié)點(diǎn)進(jìn)而獲取子節(jié)點(diǎn) NodeList list = document.getElementsByTagName("request_data"); Map<String, Object> map = new HashMap<String, Object>();//將抓取之后獲得到的值存在map中 XmlServiceImpl service = new XmlServiceImpl(); for (int i = 0; i < list.getLength(); i++) { Element element = (Element) list.item(i);//通過(guò)item(i)獲取根節(jié)點(diǎn)下的每一個(gè)子節(jié)點(diǎn) //1.識(shí)別碼 String request_token = element.getElementsByTagName("request_token").item(0).getFirstChild().getNodeValue(); map.put("request_token", request_token); //2.卡號(hào) String request_cardNum = element.getElementsByTagName("request_cardNum").item(0).getFirstChild().getNodeValue(); map.put("request_cardNum", request_cardNum); //3.持卡人姓名 String request_name = element.getElementsByTagName("request_name").item(0).getFirstChild().getNodeValue(); map.put("request_name", request_name); //4.該卡的密碼 String request_pass = element.getElementsByTagName("request_pass").item(0).getFirstChild().getNodeValue(); map.put("request_pass", request_pass); //5.本次消費(fèi)請(qǐng)求的時(shí)間 String request_time = element.getElementsByTagName("request_time").item(0).getFirstChild().getNodeValue(); map.put("request_time", request_time); //6.本次消費(fèi)的金額 String monery_count = element.getElementsByTagName("monery_count").item(0).getFirstChild().getNodeValue(); map.put("monery_count", monery_count); //7.本次消費(fèi)到的商家的名字 String shop_name = element.getElementsByTagName("shop_name").item(0).getFirstChild().getNodeValue(); map.put("shop_name", shop_name); //8.本次消費(fèi)到的商家的id String shop_id = element.getElementsByTagName("shop_id").item(0).getFirstChild().getNodeValue(); map.put("shop_id", shop_id); //9.本次消費(fèi)到的流水單號(hào) String sale_no = element.getElementsByTagName("sale_no").item(0).getFirstChild().getNodeValue(); map.put("sale_no", sale_no); }
此時(shí)輸出map對(duì)象,查看數(shù)據(jù)
{request_name=張飛, shop_id=JYJ, request_time=2021年01月25日 14:51:52, request_token=BCDBCD, monery_count=200.00, sale_no=fc4c66dc-b54b-4052-89c1-902be7569f18, request_cardNum=62284801912705, shop_name=吉野家, request_pass=123123}
返回報(bào)文
一切無(wú)誤后,返回報(bào)文
// 要返回的報(bào)文 StringBuffer resultBuffer = new StringBuffer(); resultBuffer.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); resultBuffer.append("<request_data>"); resultBuffer.append("<request_name>"+request_name+"</request_name>"); resultBuffer.append("<request_cardNum>"+request_cardNum+"</request_cardNum>"); resultBuffer.append("<request_time>"+new Dates().CurrentYMDHSMTime()+"</request_time>"); resultBuffer.append("<shop_name>"+shop_name+"</shop_name>"); resultBuffer.append("<sale_no>"+sale_no+"</sale_no>"); resultBuffer.append("<request_token>成功了</request_token>"); resultBuffer.append("</request_data>"); // 設(shè)置發(fā)送報(bào)文的格式 response.setContentType("text/xml"); response.setCharacterEncoding("UTF-8"); PrintWriter out = response.getWriter(); out.println(resultBuffer.toString()); out.flush(); out.close();
到此這篇關(guān)于Java發(fā)送報(bào)文與接收?qǐng)?bào)文的文章就介紹到這了,更多相關(guān)Java發(fā)送報(bào)文與接收?qǐng)?bào)文內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java前后端分離項(xiàng)目跨域問(wèn)題解決方案
本文主要介紹了Java前后端分離項(xiàng)目跨域問(wèn)題解決方案,其中后端基于SpringBoot,前端使用了jQuery、axios等框架,具有一定的參考價(jià)值,感興趣的可以了解一下2024-03-03java實(shí)現(xiàn)學(xué)籍管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)學(xué)籍管理系統(tǒng),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2016-12-12BeanUtils.copyProperties復(fù)制不生效的解決
這篇文章主要介紹了BeanUtils.copyProperties復(fù)制不生效的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-09-09idea?與?maven?使用過(guò)程中遇到的問(wèn)題及解決方案
最近將IDEA 升級(jí)到 IntelliJ IDEA 2021.3.2,在將maven項(xiàng)目導(dǎo)入IDEA后,maven build時(shí)報(bào)異常,這個(gè)問(wèn)題是IntelliJ IDEA 2021.3.2 不兼容導(dǎo)致的,下面小編給大家?guī)?lái)了idea?與?maven?使用過(guò)程中遇到的問(wèn)題及解決方案,感興趣的朋友一起看看吧2022-05-05使用Lombok時(shí)@JsonIgnore注解失效解決方案
這篇文章主要為大家介紹了使用Lombok時(shí)@JsonIgnore注解失效問(wèn)題解決,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-06-06在idea中g(shù)it實(shí)現(xiàn)里查看歷史代碼方式
這篇文章主要介紹了在idea中g(shù)it里查看歷史代碼的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-10-10Eclipse中@SpringBootTest注解報(bào)紅的解決方案
這篇文章主要介紹了Eclipse中@SpringBootTest注解報(bào)紅的解決方案,文中給出了原因分析和解決方案,并通過(guò)圖文結(jié)合的方式介紹的非常詳細(xì),需要的朋友可以參考下2024-03-03