java通过post方式发送接收xml信息

转自:https://blog.csdn.net/bluetjs/article/details/36899101

1.设置响应格式:


    
    
    
    
  1. response.setContentType( “text/xml”);
  2. if(request.getMethod()== null || !request.getMethod().equalsIgnoreCase( “post”)){
  3. return null;
  4. }

2.发送xml:


    
    
    
    
  1. /**
  2. * 响应xml
  3. * @param response
  4. * @param content
  5. */
  6. public static void responseContent(HttpServletResponse response,String content){
  7. try {
  8. //把xml字符串写入响应
  9. byte[] xmlData = content.getBytes();
  10. response.setContentLength(xmlData.length);
  11. ServletOutputStream os = response.getOutputStream();
  12. os.write(xmlData);
  13. os.flush();
  14. os.close();
  15. } catch (IOException e) {
  16. e.printStackTrace();
  17. }
  18. }

3.接收xml:


    
    
    
    
  1. //解析对方发来的xml数据
  2. DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
  3. DocumentBuilder db = dbf.newDocumentBuilder();
  4. Document doc = db.parse(request.getInputStream());

4.获取xml中某一节点内容:


    
    
    
    
  1. public static String getValueByTagName(Document doc, String tagName){
  2. if(doc == null || StringUtil.isNull(tagName)){
  3. return "";
  4. }
  5. NodeList pl = doc.getElementsByTagName(tagName);
  6. if(pl != null && pl.getLength() > 0){
  7. return StringUtil.dealParam(StringUtil.convertNull( pl.item( 0).getTextContent()));
  8. }
  9. return "";
  10. }

5.将xml原样转成字符串:


    
    
    
    
  1. //XML转字符串 原样取出
  2. public static String getXmlString(Document doc){
  3. TransformerFactory tf = TransformerFactory.newInstance();
  4. try {
  5. Transformer t = tf.newTransformer();
  6. t.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); //解决中文问题,试过用GBK不行
  7. t.setOutputProperty(OutputKeys.METHOD, "html");
  8. t.setOutputProperty(OutputKeys.VERSION, "4.0");
  9. t.setOutputProperty(OutputKeys.INDENT, "no");
  10. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  11. t.transform( new DOMSource(doc), new StreamResult(bos));
  12. return bos.toString();
  13. } catch (TransformerConfigurationException e) {
  14. e.printStackTrace();
  15. } catch (TransformerException e) {
  16. e.printStackTrace();
  17. }
  18. return "";
  19. }


你可能感兴趣的:(java语言)