我们在进行接口对接时,会出现报文形式的信息传递,那么下文则介绍如何处理报文形式的xml文件。
http(https)- post -xml
public static String sendHttps(String xmlInfo) {
//String a="";//请求参数
String result = "";
PrintWriter out = null;
BufferedReader in = null;
try {
trustAllHosts();
URL realUrl = new URL("https://apitest.bwjf.cn/openNozzle");
//如果是https就是下面两行代码
HttpsURLConnection conn = (HttpsURLConnection) realUrl.openConnection();
conn.setHostnameVerifier(DO_NOT_VERIFY);
//如果是http则是下面一行代码
HttpURLConnection conn = (HttpURLConnection) realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Content-Type", "text/plain;charset=utf-8");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
//加密
String base64keyString = encoder(xmlInfo);
// 发送请求参数
out.print(base64keyString);
System.out.println("发送报文:"+xmlInfo);
System.out.println("加密报文:"+base64keyString);
// flush输出流的缓冲
out.flush();
// System.out.println("响应报文:"+conn.getInputStream());
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
System.out.println("响应报文:"+result);
String key = decoder(result);
System.out.println("响应解密报文:"+key);
} catch (Exception e) {
e.printStackTrace();
} finally {// 使用finally块来关闭输出流、输入流
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
而传递报文需要对其进行base64加密解密处理,这个需要导入jar包。
/**
* 加密
*/
public static String encoder(String xmlInfo) {
byte[] bytes=xmlInfo.getBytes();
String base64keyString =new BASE64Encoder().encodeBuffer(bytes);
return base64keyString;
}
/**
* 解密
*/
public static String decoder(String xmlInfo) throws IOException {
byte[] bt = (new BASE64Decoder()).decodeBuffer(xmlInfo);
String key=new String(bt);
return key;
}
传递的xml信息封装处理,根据接口方提供的报文格式。
StringBuilder sb = new StringBuilder();
sb.append("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
sb.append(" <business id=\"CXSBZT\" >");
sb.append(" <body>");
sb.append(" <input>");
sb.append(" <jsbh>" +jsbh + "</jsbh>");
sb.append(" </input>");
sb.append(" </body>");
sb.append("</business>");
return sb.toString();