java 如何解析http请求返回的xml报文
Posted tianyumi
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java 如何解析http请求返回的xml报文相关的知识,希望对你有一定的参考价值。
xml报文解析方法有很多种,此处采用dom4j的方法。
dom4j的jar包下载地址:https://dom4j.github.io/#
1、request.getInputStream()和new SAXReader().read(输入流):
返回的报文如下:
<?xml version="1.0" encoding="UTF-8"?>
<CreateAccessKeyResponse>
<CreateAccessKeyResult>
<AccessKey>
<UserName>aaa</UserName>
<AccessKeyId>2019dfc6ab5fe433f10c</AccessKeyId>
<Status>Active</Status>
<IsPrimary>false</IsPrimary>
<SecretAccessKey>a14aeb3ac35b835d5ec4507d5667a353c77ceedc</SecretAccessKey>
</AccessKey></CreateAccessKeyResult></CreateAccessKeyResponse>
获取参数AccessKeyId的值:
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
HttpURLConnection conn = create_AccessKey(); //create_AccessKey为自己写的http请求方法
// 从request中取得输入流
InputStream inputStream = conn.getInputStream();
// 读取输入流
SAXReader reader = new SAXReader();
Document document = reader.read(inputStream);
// 得到xml根元素
Element root = document.getRootElement();
String AK = root.element("CreateAccessKeyResult").element("AccessKey").element("AccessKeyId").getTextTrim();
System.out.println("AccessKeyId="+AK+"\n");
2、用dom4j读取xml文件中的参数:
public void readXml() throws DocumentException, FileNotFoundException, IOException
String xml = System.getProperty("user.dir")+File.separator+"src"+File.separator+"test"+File.separator+"java"+File.separator+"http"+File.separator+"config.xml";
File xmlFile = new File(xml);
SAXReader reader = new SAXReader();
try
Document document = reader.read(xmlFile);
Element root = document.getRootElement();
AK = root.element("ak").getTextTrim();
SK = root.element("sk").getTextTrim();
catch (Exception e)
e.printStackTrace();
config.xml的内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<ak>0d34d3db4bab560d343c</ak>
<sk>a52628cb22b5a12642dd907075df6996b4c8a7b1</sk>
</configuration>
以上是关于java 如何解析http请求返回的xml报文的主要内容,如果未能解决你的问题,请参考以下文章