以XML形式访问远程接口获得数据

JDK提供了供我们访问url获得数据的类,核心类主要是URL,URLConnection等(详见JDK API)
下面以XML形式实现两者通信
Servlet端发送信息:

Java代码 复制代码
  1. protected void doGet(HttpServletRequest req, HttpServletResponse resp)   
  2.             throws ServletException, IOException {   
  3.         // TODO Auto-generated method stub   
  4.         resp.setCharacterEncoding("utf-8");   
  5.         PrintWriter print= resp.getWriter();   
  6.         String s = "<?xml version='1.0' encoding='utf-8'?>   
  7.                                     <web-shhzs>   
  8.                                        <return-param>    
  9.                                           <return-no>0</return-no>   
  10.                                           <return-text>执行正常</return-text>   
  11.                                         </return-param>   
  12.                                         <ptfp>   
  13.                                           <kpxsje>123456789</kpxsje>   
  14.                                         </ptfp>   
  15.                                     </web-shhzs>";   
  16.         print.write(s);   
  17.         print.flush();   
  18.         print.close();   
  19.     }  
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		resp.setCharacterEncoding("utf-8");
		PrintWriter print= resp.getWriter();
		String s = "<?xml version='1.0' encoding='utf-8'?>
                                    <web-shhzs>
                                       <return-param> 
                                          <return-no>0</return-no>
                                          <return-text>执行正常</return-text>
                                        </return-param>
                                        <ptfp>
                                          <kpxsje>123456789</kpxsje>
                                        </ptfp>
                                    </web-shhzs>";
		print.write(s);
		print.flush();
		print.close();
	}


获得访问返回信息,以字符串返回:

Java代码 复制代码
  1.     public static String getXML(String sh,String type,String date) throws IOException{   
  2.         StringBuffer urlStr = new StringBuffer("http://localhost:8888/Hello/getDom.do");   
  3. //      urlStr.append("?param1=").append(sh)   
  4. //            .append("&param2=").append(type)   
  5. //            .append("&param3=").append(date);   
  6.         URL url = new URL(urlStr.toString());   
  7.         URLConnection URLconnection = url.openConnection();   
  8.         HttpURLConnection httpConnection = (HttpURLConnection)URLconnection;   
  9.         int responseCode = httpConnection.getResponseCode();   
  10. //      FileOutputStream fos=new FileOutputStream("d://line.txt",true);      
  11. //      DataOutputStream out=new DataOutputStream(fos);    
  12.         StringBuffer totalXML = new StringBuffer("");   
  13.         if(responseCode == HttpURLConnection.HTTP_OK){   
  14.             InputStream httpStream = httpConnection.getInputStream();   
  15.             BufferedReader bufferReader = new BufferedReader(new InputStreamReader(httpStream));   
  16.             String currLine = "";   
  17.             while((currLine=bufferReader.readLine())!=null){   
  18. //              out.writeBytes(new   String(currLine.getBytes(),"utf-8"));      
  19. //              out.writeBytes("\r\n");      
  20.                 totalXML.append(currLine);   
  21.             }   
  22.         }   
  23. //      fos.close();      
  24. //      out.close();      
  25.         return totalXML.toString();   
  26.     }  
	public static String getXML(String sh,String type,String date) throws IOException{
		StringBuffer urlStr = new StringBuffer("http://localhost:8888/Hello/getDom.do");
//		urlStr.append("?param1=").append(sh)
//			  .append("&param2=").append(type)
//			  .append("&param3=").append(date);
		URL url = new URL(urlStr.toString());
		URLConnection URLconnection = url.openConnection();
		HttpURLConnection httpConnection = (HttpURLConnection)URLconnection;
		int responseCode = httpConnection.getResponseCode();
//		FileOutputStream fos=new FileOutputStream("d://line.txt",true);   
//	    DataOutputStream out=new DataOutputStream(fos); 
	    StringBuffer totalXML = new StringBuffer("");
		if(responseCode == HttpURLConnection.HTTP_OK){
			InputStream httpStream = httpConnection.getInputStream();
			BufferedReader bufferReader = new BufferedReader(new InputStreamReader(httpStream));
			String currLine = "";
			while((currLine=bufferReader.readLine())!=null){
//				out.writeBytes(new   String(currLine.getBytes(),"utf-8"));   
//	            out.writeBytes("\r\n");   
				totalXML.append(currLine);
			}
		}
//		fos.close();   
//      out.close();   
		return totalXML.toString();
	}


用DOM4J解析XML获得相应信息封装为Map

Java代码 复制代码
  1. public static Map getFpxx(String text){   
  2.        
  3.     Map map = new HashMap();   
  4.     Document document;   
  5.     try {   
  6.                  //dom4j解析字符串为xml   
  7.     document = DocumentHelper.parseText(text);   
  8.         Element root = document.getRootElement();   
  9.         Element e1 = root.element("return-param");   
  10.         if(null!=e1){   
  11.              if(null!=e1){   
  12.                  String state = e1.element("return-text").getStringValue();   
  13.                  System.out.println(state);   
  14.                  map.put("state", state);   
  15.                     
  16.              }   
  17.              Element e2 = root.element("ptfp");   
  18.              if(null!=e2){   
  19.                  String kpxsje = e2.element("kpxsje").getStringValue();   
  20.                  System.out.println(kpxsje);   
  21.                  map.put("result", kpxsje);   
  22.              }   
  23.          }   
  24.     } catch (DocumentException e) {   
  25.         // TODO Auto-generated catch block   
  26.         e.printStackTrace();   
  27.         logger.error("字符串转换为xml时出错");   
  28.     }   
  29.     return map;   
  30. }  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值