Java發(fā)送報(bào)文與接收報(bào)文的實(shí)例代碼
報(bào)文(message)是網(wǎng)絡(luò)中交換與傳輸?shù)臄?shù)據(jù)單元,即站點(diǎn)一次性要發(fā)送的數(shù)據(jù)塊。報(bào)文包含了將要發(fā)送的完整的數(shù)據(jù)信息,其長短很不一致,長度不限且可變。
個(gè)人理解:從客戶端把字符串寫入字節(jié)數(shù)組流中傳達(dá)至服務(wù)端,但是此字符串是XML格式的,然后到了服務(wù)端,使用字節(jié)數(shù)組進(jìn)行獲取該字符串,再獲取該字符串的document對象(因?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)為流寫入
/**
* @desc 將xml轉(zhuǎn)為流寫入
* @param servletConnection
* @throws IOException
*/
public void xmlWriteStream(HttpURLConnection servletConnection) throws IOException {
// 創(chuàng)建流,寫入xml數(shù)據(jù)
OutputStream ouput = servletConnection.getOutputStream();
// 調(diào)用方法獲取xml字符串
String str = xmlToString();
System.out.println(str);
// 將xml字符串轉(zhuǎn)為btye數(shù)組寫入流
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"); // 請求類型為post
servletConnection.setDoOutput(true); // 是否可讀
servletConnection.setDoInput(true); // 是否可寫
servletConnection.setAllowUserInteraction(true); // 是否可交互
return servletConnection;
}
獲取服務(wù)端反饋回來的結(jié)果
/**
* @desc 獲取服務(wù)端反饋回來的結(jié)果
* @param servletConnection
* @throws IOException
*/
public void getResponseResult(HttpURLConnection servletConnection)
throws IOException {
System.out.println("===============**服務(wù)端的返回值**==================");
// 獲取返回的數(shù)據(jù)
InputStream inputStream = servletConnection.getInputStream();//獲取反饋回來的流
//創(chuàng)建一個(gè)緩沖讀取的reader對象
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
//創(chuàng)建一個(gè)能夠承接返回來值得sb
StringBuffer sb = new StringBuffer();
//創(chuàng)建一個(gè)能夠臨時(shí)存儲(chǔ)讀取一行信息的變量
String strMessage = "";
//開始循環(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("=================開始發(fā)送報(bào)文=================");
// 建立連接
HttpURLConnection servletConnection = cerateServletUrl();
// 寫入數(shù)據(jù)
xmlWriteStream(servletConnection);
// 獲取返回?cái)?shù)據(jù)
getResponseResult(servletConnection);
} catch (java.net.ConnectException e) {
System.out.println("客戶端與服務(wù)端連接異常,請?jiān)俅螄L試");
}
}
接收報(bào)文
服務(wù)端使用web項(xiàng)目進(jìn)行構(gòu)建
在service中設(shè)置編碼集
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
獲取客戶端發(fā)送過來的報(bào)文
//----------------通過request.getInputStream()獲取輸入的流----------------------
// 指定每次8kb
final int BUFFER_SIZE = 8 * 1024;
byte[] buffer = new byte[BUFFER_SIZE];
// 獲取輸出流,與客戶端的輸出流相對應(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) {
// 寫入至字節(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ā)送來的報(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)文之后,開始解析報(bào)文,即為解析Xml
//1.初始化jdk中的用來解析xml的dom工廠
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
//2:獲得具體的dom解析器
DocumentBuilder db = dbf.newDocumentBuilder();
//3: 解析一個(gè)xml文檔,獲得Document對象(根結(jié)點(diǎn))
InputSource is = new InputSource(new StringReader(bodyData));
Document document = null;
try{
document = db.parse(is);//將流轉(zhuǎn)換成document對象
}catch(Exception e){
return ;
}
獲取完document對象之后,開始解析
//通過抓取根節(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);//通過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)請求的時(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對象,查看數(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)文
一切無誤后,返回報(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)文與接收報(bào)文的文章就介紹到這了,更多相關(guān)Java發(fā)送報(bào)文與接收報(bào)文內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Java?Chassis3的多種序列化方式支持技術(shù)解密
這篇文章主要為大家介紹了Java?Chassis?3多種序列化方式支持技術(shù)解密,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2024-01-01
使用JavaWeb webSocket實(shí)現(xiàn)簡易的點(diǎn)對點(diǎn)聊天功能實(shí)例代碼
這篇文章主要介紹了使用JavaWeb webSocket實(shí)現(xiàn)簡易的點(diǎn)對點(diǎn)聊天功能實(shí)例代碼的相關(guān)資料,內(nèi)容介紹的非常詳細(xì),具有參考借鑒價(jià)值,感興趣的朋友一起學(xué)習(xí)吧2016-05-05
教你用springboot連接mysql并實(shí)現(xiàn)增刪改查
今天教各位小伙伴用springboot連接mysql并實(shí)現(xiàn)增刪改查功能,文中有非常詳細(xì)的步驟及代碼示例,對正在學(xué)習(xí)Java的小伙伴們有非常好的幫助,需要的朋友可以參考下2021-05-05
詳解Java如何判斷ResultSet結(jié)果集是否為空
ResultSet 表示 select 語句的查詢結(jié)果集。這篇文章主要為大家詳細(xì)介紹了Java如何判斷ResultSet結(jié)果集是否為空,感興趣的可以了解一下2023-02-02
spring+springmvc整合mabytis時(shí)mapper注入失敗問題解決方法
這篇文章主要介紹了spring+springmvc整合mabytis時(shí)mapper注入失敗問題解決方法 ,需要的朋友可以參考下2017-08-08

