公司要求写一个接口供客户调用,客户那边传过来XML的请求数据,接口用来处理数据并返回一些参数。主要通过HTTP POST方式发送XML请求数据,相应的接口对XML请求做出处理后返回参数。主要的流程和代码如下:
首先写一个接口,大致流程为:1、创建两个bean,传送的bean(SendXMLBean.java)返回bean (ReturnXMLBean.java)→2、创建一个servlet接口。
servlet接口中的流程:1、接收传递过来的xml→2、把xml转化为bean→3、SendXMLBean去set接收get到的参数→4、对PDF进行数字签名→5、存入数据库中→6、返回参数。
具体步骤和代码:
1、创建两个bean,传送的bean(SendXMLBean.java):
public class SendXMLBean {
private String areaCode;
private String businessId;
private String businessDate;
private String customerName;
private String idCard;
private String mobile;
private String telNo;
private String customerAddress;
private String businessType;
private String authType;
private String optCode;
private String ext1;
private String ext2;
private String ext3;
private String ext4;
private String ext5;
private String PDFBase64;
private String BusinessPoint;
private String accPDFBase64;
public String getBusinessPoint() {
return BusinessPoint;
}
public void setBusinessPoint(String businessPoint) {
BusinessPoint = businessPoint;
}
public String getAreaCode() {
return areaCode;
}
public void setAreaCode(String areaCode) {
this.areaCode = areaCode;
}
public String getBusinessId() {
return businessId;
}
public void setBusinessId(String businessId) {
this.businessId = businessId;
}
public String getBusinessDate() {
return businessDate;
}
public void setBusinessDate(String businessDate) {
this.businessDate = businessDate;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getIdCard() {
return idCard;
}
public void setIdCard(String idCard) {
this.idCard = idCard;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getTelNo() {
return telNo;
}
public void setTelNo(String telNo) {
this.telNo = telNo;
}
public String getCustomerAddress() {
return customerAddress;
}
public void setCustomerAddress(String customerAddress) {
this.customerAddress = customerAddress;
}
public String getBusinessType() {
return businessType;
}
public void setBusinessType(String businessType) {
this.businessType = businessType;
}
public String getAuthType() {
return authType;
}
public void setAuthType(String authType) {
this.authType = authType;
}
public String getOptCode() {
return optCode;
}
public void setOptCode(String optCode) {
this.optCode = optCode;
}
public String getExt1() {
return ext1;
}
public void setExt1(String ext1) {
this.ext1 = ext1;
}
public String getExt2() {
return ext2;
}
public void setExt2(String ext2) {
this.ext2 = ext2;
}
public String getExt3() {
return ext3;
}
public void setExt3(String ext3) {
this.ext3 = ext3;
}
public String getExt4() {
return ext4;
}
public void setExt4(String ext4) {
this.ext4 = ext4;
}
public String getExt5() {
return ext5;
}
public void setExt5(String ext5) {
this.ext5 = ext5;
}
public String getPDFBase64() {
return PDFBase64;
}
public void setPDFBase64(String pDFBase64) {
PDFBase64 = pDFBase64;
}
public String getAccPDFBase64() {
return accPDFBase64;
}
public void setAccPDFBase64(String accPDFBase64) {
this.accPDFBase64 = accPDFBase64;
}
}
返回的bean(ReturnXMLBean.java):
public class ReturnXMLBean {
private String areaCode;
private String businessID;
private boolean isSuccess;
private String errorMsg;
public String getAreaCode() {
return areaCode;
}
public void setAreaCode(String areaCode) {
this.areaCode = areaCode;
}
public String getBusinessID() {
return businessID;
}
public void setBusinessID(String businessID) {
this.businessID = businessID;
}
public boolean isSuccess() {
return isSuccess;
}
public void setSuccess(boolean isSuccess) {
this.isSuccess = isSuccess;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
}
2、创建一个servlet接口:
public class ImportXmlServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected static Logger logger = Logger.getLogger(ImportXmlServlet.class);
// 授权码
private static final String authCode = "WDDSED12KINGGRID";
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws IOException {
// 1.取得输入流入参XML ,请勿移动此行 ,否则得不到数据
String importXml = new String();
importXml = inputStream2String(request.getInputStream());
String method = request.getParameter("method");
response.setContentType("application/octet-stream");
try {
if ("importPDF".equals(method)) {
System.out.println(importXml);
importPdf(importXml, request, response);
} else if ("uploadPDF".equals(method)) {
uploadPdf(importXml, request, response);
} else if ("savePdf".equals(method)) {
savePdf(importXml, request, response);
} else {
throw new Exception("param [method] is not exits! ");
}
} catch (Exception e) {
logger.error(e, e);
BufferedOutputStream bos = null;
try {
bos = new BufferedOutputStream(response.getOutputStream());
String returnXml = "error";
if ("importPDF".equals(method)) {
IReturnXML returnXML = new IReturnXML();
returnXML.setSuccess(false);
returnXML.setErrorMsg(e.getMessage());
BeanToXml beanToXml = new BeanToXml();
returnXml = beanToXml.createIRenurnXML(returnXML);
} else if ("uploadPDF".equals(method)){
UReturnXML returnXML = new UReturnXML();
returnXML.setSuccess(false);
returnXML.setErrorMsg(e.getMessage());
BeanToXml beanToXml = new BeanToXml();
returnXml = beanToXml.createURenurnXML(returnXML);
}else if ("savePdf".equals(method)){
ReturnXMLBean returnXMLBean = new ReturnXMLBean();
returnXMLBean.setSuccess(false);
returnXMLBean.setErrorMsg(e.getMessage());
BeanToXml beanToXml = new BeanToXml();
returnXml = beanToXml.createReturnXMLBean(returnXMLBean);
}
bos.write(returnXml.getBytes("UTF-8"));
bos.flush();
bos.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
if (null != bos) {
try {
bos.close();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}
}
private void savePdf(String importXml, HttpServletRequest request, HttpServletResponse response) throws Exception {
// TODO Auto-generated method stub
//writeBytes(new File("D:\\getSave.xml"),importXml.getBytes());
XmlToBean xmlToBean =new XmlToBean();
SendXMLBean sendXMLBean = xmlToBean.getSendXMLBean(importXml);
ReturnXMLBean returnXMLBean=new ReturnXMLBean();
returnXMLBean.setAreaCode(sendXMLBean.getAreaCode());
returnXMLBean.setBusinessID(sendXMLBean.getBusinessId());
returnXMLBean.setSuccess(false);
SendXMLBean sendxmlbean=new SendXMLBean();
sendxmlbean.setAreaCode(sendXMLBean.getAreaCode());
sendxmlbean.setCustomerName(sendXMLBean.getCustomerName());
sendxmlbean.setAuthType(sendXMLBean.getAuthType());
sendxmlbean.setBusinessId(sendXMLBean.getBusinessId());
sendxmlbean.setBusinessType(sendXMLBean.getBusinessType());
sendxmlbean.setBusinessDate(sendXMLBean.getBusinessDate());
sendxmlbean.setIdCard(sendXMLBean.getIdCard());
sendxmlbean.setMobile(sendXMLBean.getMobile());
sendxmlbean.setTelNo(sendXMLBean.getTelNo());
sendxmlbean.setCustomerAddress(sendXMLBean.getCustomerAddress());
sendxmlbean.setOptCode(sendXMLBean.getOptCode());
sendxmlbean.setBusinessPoint(sendXMLBean.getBusinessPoint());
sendxmlbean.setAccPDFBase64(sendXMLBean.getAccPDFBase64());
sendxmlbean.setExt1(sendXMLBean.getExt1());
sendxmlbean.setExt2(sendXMLBean.getExt2());
sendxmlbean.setExt3(sendXMLBean.getExt3());
sendxmlbean.setExt4(sendXMLBean.getExt4());
sendxmlbean.setExt5(sendXMLBean.getExt5());
PdfSignVerfityImpl pdfSignVerfity=new PdfSignVerfityImpl();
StringBuffer stringBuffer=new StringBuffer();
String pdfNoSignFiles=base64StringToPDF(request,sendXMLBean.getPDFBase64());
String pdfSignedFiles=PathUrlUtil.getRealFilePath(request,stringBuffer,"SignedFiles",".pdf");
System.out.println("未进行签名的地址:"+pdfNoSignFiles);
System.out.println("已进行签名的地址:"+pdfSignedFiles);
pdfSignVerfity.sign(pdfNoSignFiles, pdfSignedFiles, sendxmlbean.getAreaCode());
Base64 base64=new Base64();
String pdfBase64 =new String(base64.encode(readBytes(new File(pdfSignedFiles))));
String pDFBase64 = MD5Util.stringToMD5(pdfBase64, "utf-8");
sendxmlbean.setPDFBase64(pDFBase64);
OrderLogDao orderLogManager = new OrderLogDao();
if(!orderLogManager.saveOrderLogTest(sendxmlbean)){
System.out.println("error");
};
System.out.println(sendxmlbean.getAreaCode());
//OrderLogManager newOrderLogManager = OrderLogManager.getInstance();
//OrderLogTest orderLog = new OrderLogTest();
BeanToXml beanToXml = new BeanToXml();
String returnXml = beanToXml.createReturnXMLBean(returnXMLBean);
//logger.info(returnXml);
// 保存一份用于测试
// writeBytes(new File("D:\\pdf\\returnXml.xml"), returnXml.getBytes());
BufferedOutputStream bos = new BufferedOutputStream(
response.getOutputStream());
// 13.输出返回流
bos.write(returnXml.getBytes("UTF-8"));
bos.flush();
bos.close();
}
public String base64StringToPDF(HttpServletRequest request,String base64sString){
BufferedInputStream bin = null;
FileOutputStream fout = null;
BufferedOutputStream bout = null;
BASE64Decoder decoder = new sun.misc.BASE64Decoder();
String pdfNoSignFiles="";
try {
//将base64编码的字符串解码成字节数组
byte[] bytes = decoder.decodeBuffer(base64sString);
//apache公司的API
//byte[] bytes = Base64.decodeBase64(base64sString);
//创建一个将bytes作为其缓冲区的ByteArrayInputStream对象
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
//创建从底层输入流中读取数据的缓冲输入流对象
bin = new BufferedInputStream(bais);
//指定输出的文件
StringBuffer stringBuffer=new StringBuffer();
pdfNoSignFiles=PathUrlUtil.getRealFilePath(request,
stringBuffer, "NoSignFiles", ".pdf");
//创建到指定文件的输出流
fout = new FileOutputStream(pdfNoSignFiles);
//为文件输出流对接缓冲输出流对象
bout = new BufferedOutputStream(fout);
byte[] buffers = new byte[1024];
int len = bin.read(buffers);
while(len != -1){
bout.write(buffers, 0, len);
len = bin.read(buffers);
}
//刷新此输出流并强制写出所有缓冲的输出字节,必须这行代码,否则有可能有问题
bout.flush();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
bin.close();
fout.close();
bout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return pdfNoSignFiles;
}
public static byte[] readBytes(File file) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
InputStream fis = new FileInputStream(file);
InputStream is = new BufferedInputStream(fis);
int count = 0;
byte[] buf = new byte[16384];
while ( (count = is.read(buf)) != -1) {
if (count > 0) {
baos.write(buf, 0, count);
}
}
is.close();
}
catch (Exception e) {
}
return baos.toByteArray();
}
public static void writeBytes(File file, byte[] data) {
try {
OutputStream fos = new FileOutputStream(file);
OutputStream os = new BufferedOutputStream(fos);
os.write(data);
os.close();
} catch (Exception e) {
}
}
public void inputStream2File(InputStream is, String saveFilePath)
throws IOException {
OutputStream os = new FileOutputStream(saveFilePath);// 建立一个上传文件的输出流"D:\\get.xml"
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = is.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);// 传过来的文件写入文件
}
os.flush();
os.close();
}
3、XML转化为bean(XmlToBean.java)代码:
public class XmlToBean {
protected static Logger logger = Logger.getLogger(XmlToBean.class);
public SendXMLBean getSendXMLBean(String importXml) throws Exception {
XMLUtil xMLUtil = XMLUtil.getInsance(new ByteArrayInputStream(importXml.getBytes("UTF-8")));
SendXMLBean sendXMLBean = new SendXMLBean();
sendXMLBean.setAreaCode(xMLUtil.getSingleElementText("XMLData/AreaCode"));
sendXMLBean.setBusinessId(xMLUtil.getSingleElementText("XMLData/BusinessId"));
sendXMLBean.setBusinessDate(xMLUtil.getSingleElementText("XMLData/BusinessDate"));
sendXMLBean.setCustomerName(xMLUtil.getSingleElementText("XMLData/CustomerName"));
sendXMLBean.setIdCard(xMLUtil.getSingleElementText("XMLData/IdCard"));
sendXMLBean.setMobile(xMLUtil.getSingleElementText("XMLData/Mobile"));
sendXMLBean.setTelNo(xMLUtil.getSingleElementText("XMLData/TelNo"));
sendXMLBean.setCustomerAddress(xMLUtil.getSingleElementText("XMLData/CustomerAddress"));
sendXMLBean.setBusinessType(xMLUtil.getSingleElementText("XMLData/BusinessType"));
sendXMLBean.setAuthType(xMLUtil.getSingleElementText("XMLData/AuthType"));
sendXMLBean.setOptCode(xMLUtil.getSingleElementText("XMLData/OptCode"));
sendXMLBean.setExt1(xMLUtil.getSingleElementText("XMLData/Ext1"));
sendXMLBean.setExt2(xMLUtil.getSingleElementText("XMLData/Ext2"));
sendXMLBean.setExt3(xMLUtil.getSingleElementText("XMLData/Ext3"));
sendXMLBean.setExt4(xMLUtil.getSingleElementText("XMLData/Ext4"));
sendXMLBean.setExt5(xMLUtil.getSingleElementText("XMLData/Ext5"));
sendXMLBean.setPDFBase64(xMLUtil.getSingleElementText("XMLData/PDFBase64"));
sendXMLBean.setAccPDFBase64(xMLUtil.getSingleElementText("XMLData/AccPDFBase64"));
return sendXMLBean;
}
}
4、Bean转化为XML(BeanToXml)代码:
public class BeanToXml {
protected static Logger logger = Logger.getLogger(BeanToXml.class);
public String createReturnXMLBean(ReturnXMLBean returnXMLBean) {
String xml = "";
Element XMLData = new Element("XMLData");
Element areaCode = new Element("AreaCode");
areaCode.setText(returnXMLBean.getAreaCode());
Element businessID = new Element("BusinessID");
businessID.setText(returnXMLBean.getBusinessID());
Element isSuccess = new Element("IsSuccess");
isSuccess.setText(String.valueOf(returnXMLBean.isSuccess()));
Element errorMsg = new Element("ErrorMsg");
errorMsg.setText(returnXMLBean.getErrorMsg());
// 表头
XMLData.addContent(areaCode);
XMLData.addContent(businessID);
XMLData.addContent(isSuccess);
XMLData.addContent(errorMsg);
Document doc = new Document(XMLData);
XMLOutputter out = new XMLOutputter();
Format format = Format.getCompactFormat();
format.setEncoding("UTF-8");
format.setIndent("\t");
out.setFormat(format);// 设置文件编码,默认为UTF-8
ByteArrayOutputStream bo = new ByteArrayOutputStream();
try {
out.output(doc, bo);
logger.info("createImportPdf:"
+ new String(bo.toByteArray(), "UTF-8"));
xml = new String(bo.toByteArray(), "UTF-8");
} catch (Exception e) {
logger.error(e.getMessage());
}
return xml;
}
}
5、写一个测试类,测试代码如下:
package com.goldgrid.post.xtest;
public class TestSRXML {
public static void main(String[] args) throws Exception {
// 1.入参对象
OrderLogTest savePDF = new OrderLogTest();
Base64 base64 = new Base64();
// 2.设置一单清XML
/**
* //改为传订单号,减少网络传输
*
* FileInputStream xmlin; try { xmlin = new
* FileInputStream("d:/pdf/73.xml"); byte[] buff = new
* byte[xmlin.available()]; xmlin.read(buff); String xmlInfo = new
* String(buff, "UTF-8");
*
* // 对XML做base64加码 xmlInfo = new
* String(base64.encode(xmlInfo.getBytes()));
* uploadPDF.setXmlInfoBase64(xmlInfo);
*
* } catch (Exception e) { // TODO Auto-generated catch block
* e.printStackTrace(); }
**/
// 3.设置savePDF
String pdfBase64 = new String(base64.encode(readBytes(new File(
"c:/pdf.pdf"))));
savePDF.setAreaCode("0514");
savePDF.setBusinessId("666666666");
savePDF.setBusinessDate("2018-5-24");
savePDF.setCustomerName("重庆有线");
savePDF.setBusinessType("有线电视");
savePDF.setAuthType("不知道是啥");
savePDF.setPDFBase64(pdfBase64);
savePDF.setIdCard("6217005062584568955");
savePDF.setMobile("13027206888");
savePDF.setTelNo("110");
savePDF.setCustomerAddress("紫阳大道");
savePDF.setOptCode("007");
savePDF.setBusinessPoint("江西师大");
savePDF.setAccPDFBase64("base64");
BeanToXml beanToXml = new BeanToXml();
// 5.入参对象转为XML
String importXml = beanToXml.createSaveXML(savePDF);
// 6.保存入参对象XML
String importXmlPath = "d:\\SaveXML.xml";
writeBytes(new File(importXmlPath), importXml.getBytes("UTF-8"));
TestSRXML uxf = new TestSRXML();
// 5.POST入参对象XML,返回回执PDFXML
String returnXml = uxf
.uploadXMLFile(importXmlPath,
"http://localhost:8080/iSolutions-BDE_CQYX/ImportXml?method=savePdf");
writeBytes(new File("d:\\SaveReturnXML.xml"),
returnXml.getBytes("UTF-8"));
XmlToBean xmlToBean = new XmlToBean();
// 7.解析返回XML为对象
SaveReturnXML returnSavePDF = xmlToBean.getReturnSavePdf(returnXml);
System.out.print(returnXml);
if (returnSavePDF.isSuccess()) {
System.out.println("上传成功!");
} else {
System.out.println(returnSavePDF.getErrorMsg());
}
}
public synchronized String uploadXMLFile(final String importXmlPath,
final String strURL) {
String result = null;
try {
URL url = new URL(strURL);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
conn.setRequestProperty("enctype", "multipart/form-data");
conn.setRequestProperty("contentType", "charset=UTF-8");
conn.setRequestMethod("POST");
// 上传xml文件
DataInputStream file = new DataInputStream(new FileInputStream(
new File(importXmlPath)));
OutputStream out = conn.getOutputStream();
int bytesOut = 0;
byte[] bufferOut = new byte[8192];
while ((bytesOut = file.read(bufferOut, 0, 8192)) != -1) {
out.write(bufferOut, 0, bytesOut);
}
out.flush();
out.close();
// 获得上传的结果
InputStream isResult = conn.getInputStream();
result = inputStream2String(isResult);
} catch (Exception e) {
result = "ERROR";
System.out.println(e.getMessage());
}
return result;
}
public String inputStream2String(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int i = -1;
while ((i = is.read()) != -1) {
baos.write(i);
}
return baos.toString();
}
public static void writeBytes(File file, byte[] data) {
try {
OutputStream fos = new FileOutputStream(file);
OutputStream os = new BufferedOutputStream(fos);
os.write(data);
os.close();
} catch (Exception e) {
}
}
public static byte[] readBytes(File file) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
InputStream fis = new FileInputStream(file);
InputStream is = new BufferedInputStream(fis);
int count = 0;
byte[] buf = new byte[16384];
while ((count = is.read(buf)) != -1) {
if (count > 0) {
baos.write(buf, 0, count);
}
}
is.close();
} catch (Exception e) {
}
return baos.toByteArray();
}
}
6、将需要的数据存入数据库:
public boolean saveOrderLogTest(SendXMLBean sendXMLBean){
boolean b = false;
StringBuffer sql = new StringBuffer();
sql.append("insert into t_order_log_test (areaCode, businessID , businessDate,customerName, idCard, " +
" Mobile, TelNo, customerAddress, businessType, authType, optCode " +
" , Ext1, Ext2, Ext3, Ext4, Ext5, PDFBASE64, accpdfbase64) " +
" values( ?, ?, ?, ?,?, " +
" ?, ?, ?, ?, ?, ? ," +
" ?, ?, ?, ?, ?, ?, ?)" );
Object[] params = new Object[18];
int[] types = new int[18];
params[0] = sendXMLBean.getAreaCode();
types[0]= Types.VARCHAR;
params[1] = sendXMLBean.getBusinessId();
types[1] = Types.VARCHAR;
params[2] = sendXMLBean.getBusinessDate();
types[2] = Types.VARCHAR;
params[3] = sendXMLBean.getCustomerName();
types[3] = Types.VARCHAR;
params[4] = sendXMLBean.getIdCard();
types[4] = Types.VARCHAR;
params[5] = sendXMLBean.getMobile();
types[5] = Types.VARCHAR;
params[6] = sendXMLBean.getTelNo();
types[6] = Types.VARCHAR;
params[7] = sendXMLBean.getCustomerAddress();
types[7] = Types.VARCHAR;
params[8] = sendXMLBean.getBusinessType();
types[8] = Types.VARCHAR;
params[9] = sendXMLBean.getAuthType();
types[9] = Types.VARCHAR;
params[10] = sendXMLBean.getOptCode();
types[10] = Types.VARCHAR;
params[11] = sendXMLBean.getExt1();
types[11] = Types.VARCHAR;
params[12] = sendXMLBean.getExt2();
types[12] = Types.VARCHAR;
params[13] = sendXMLBean.getExt3();
types[13] = Types.VARCHAR;
params[14] = sendXMLBean.getExt4();
types[14] = Types.VARCHAR;
params[15] = sendXMLBean.getExt5();
types[15] = Types.VARCHAR;
params[16] = sendXMLBean.getPDFBase64();
types[16] = Types.VARCHAR;
params[17] = sendXMLBean.getAccPDFBase64();
types[17] = Types.VARCHAR;
try {
b = update(sql.toString(), params, types) > 0;
} catch (SQLException e) {
logger.error(e);
}
return b;
}