JDK提供了供我们访问url获得数据的类,核心类主要是URL,URLConnection等(详见JDK API)
下面以XML形式实现两者通信
Servlet端发送信息:
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(); }
获得访问返回信息,以字符串返回:
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("¶m2=").append(type)// .append("¶m3=").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
public static Map getFpxx(String text){ Map map = new HashMap(); Document document; try { //dom4j解析字符串为xml document = DocumentHelper.parseText(text); Element root = document.getRootElement(); Element e1 = root.element("return-param"); if(null!=e1){ if(null!=e1){ String state = e1.element("return-text").getStringValue(); System.out.println(state); map.put("state", state); } Element e2 = root.element("ptfp"); if(null!=e2){ String kpxsje = e2.element("kpxsje").getStringValue(); System.out.println(kpxsje); map.put("result", kpxsje); } } } catch (DocumentException e) { // TODO Auto-generated catch block e.printStackTrace(); logger.error("字符串转换为xml时出错"); } return map; }