关于微信支付回调XML数据的处理
- 微信回调请求的数据是XML格式
- 接受需要处理XML
难点
- 测试发送XML
- 接受XML
本来想在本地测试模拟发送XML数据,然后本地接收处理,结果遇到XML发送失败或接收失败的问题.
main 方法
URL url = new URL("http://localhost:8080/pay_service/wxnotify_url");
URLConnection con = url.openConnection();
con.setDoOutput(true);
con.setRequestProperty("Pragma:", "no-cache");
con.setRequestProperty("Cache-Control", "no-cache");
con.setRequestProperty("Content-Type", "text/xml");
OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
String xmlInfo = " String xmlStr="<xml><return_code><![CDATA[SUCCESS]]></return_code></xml>"; //XML数据 并不是完整的.
out.write(xmlInfo);
//out.write(new String(xmlInfo.getBytes("ISO-8859-1")));//如果想发送其他编码格式
out.flush();
out.close();//理解为把数据装入包中,但没有发送 1
con.getInputStream();//理解为,将包给服务器然后祈求回应,若没有此步骤相当于未向服务器发送请求 2
//或者,如果要处理服务器返回的数据则读取,因为我是单方面发送,所以服务器并不会返回数据
BufferedReader br = new BufferedReader(new InputStreamReader(con
.getInputStream()));
String line = "";
for (line = br.readLine(); line != null; line = br.readLine()) {
System.out.println(line);
}
服务器端
@Action(value = "/wxnotify_url")
public void wxNotifyUrl() throws IOException {
// 微信支付回调
HttpServletRequest request = ServletActionContext.getRequest();
String inputLine = null;
// 接收到的数据
StringBuffer recieveData = new StringBuffer();
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(
request.getInputStream(), "UTF-8"));
while ((inputLine = in.readLine()) != null) {
recieveData.append(inputLine);
}
} catch (IOException e) {
} finally {
try {
if (null != in) {
in.close();
}
} catch (IOException e) {
}
}
try {
Map<String, String> map = WXPayUtil.xmlToMap(recieveData.toString());//微信jdk 中一个XML转MAP的工具
System.out.println(map);//将会显示{return_code=SUCCESS}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
啊XJBLZ..