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

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("&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

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值