Get⽅式请求并获取XML数据格式st;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.URI;
import java.URISyntaxException;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.hods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import lUtils;
public class WriteResponse2XML{
public static void main(String[] args) throws
URISyntaxException, ClientProtocolException, IOException, DocumentException{
//Get请求的参数
final String URL = "search.ifeng/searchxml";
final String PARAM = "q=三星&df=2013-7-1&n=3";
//XML⽂件输出的位置
final String FILE_PATH = "./l";
//初始化log4j
Logger log = Logger(WriteResponse2XML.class);
HttpClient httpClient = new DefaultHttpClient();
//Get请求
HttpGet httpGet = new HttpGet(URL);
//拼装字符串
httpGet.setURI(new URI().toString()+"?"+PARAM));
//System.out.println(new URI().toString()));
//发请求
HttpResponse response = ute(httpGet);
StatusLine().getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = Entity();
BufferedReader br = new BufferedReader(new Content(),"UTF-8"));
//将获取的response写⼊到xml⽂件中(不是必要步骤)
Document document = Document(br);
xmlUtils.document2XML(document, FILE_PATH);
//解析XML⽂件,并验证其中的关键值
Element rootElement = RootElement();
//获取list节点,验证参数n是否正确
List<Element> list = rootElement.elements("item");
if(3 == list.size()) {
log.info("请求中参数n=3,也就是每页有3条记录。实际返回的response中也是每页有3条记录。");使用dom4j解析xml文件
}else {
log.info("请求中参数n=3,也就是每页有3条记录。实际返回的response中也是每页有"+list.size()+"条记录,与请求参数不符");
}
for(int i=0; i<list.size(); i++) {
String title = (i).element("Doc_Title").getText();
//System.out.println(title);
//验证参数q是否正确,q是查的关键字
ains("三星")) {
log.info("请求中参数q=三星,也就查的关键字。实际返回的第"+(i+1)+"条记录中包含该关键字。");
}else {
log.info("第"+(i+1)+"条记录中没有包含该关键字");
}
}
}else {
<("请求失败,状态码为:"+StatusLine().getStatusCode());
}
}
}
返回的response
<?xml version="1.0" encoding="UTF-8"?>
<list>
<numFound>34,161</numFound>
<max_page>11,387</max_page>
<QTime>343</QTime>
<item>
<Doc_Date><![CDATA[2012-03-21]]></Doc_Date>
<Doc_Title><![CDATA[宁波三星电⽓股份有限公司关于重⼤经营合同中标的提⽰性公告]]></Doc_Title>
<Doc_Url><![CDATA[finance.ifeng/roll/20120321/5779454.shtml]]></Doc_Url>
</item>
<item>
<Doc_Date><![CDATA[2012-03-21]]></Doc_Date>
<Doc_Title><![CDATA[时尚潮流造型⼩巧安卓机三星I579再爆新低]]></Doc_Title>
<Doc_Url><![CDATA[tech.ifeng/digi/mobile/price/detail_2012_03/21/13329289_0.shtml]]></Doc_Url> </item>
<item>
<Doc_Date><![CDATA[2012-03-21]]></Doc_Date>
<Doc_Title><![CDATA[ST三星:独⽴董事关于控股股东及其他关联⽅占⽤资⾦情况的说明及独⽴意见]]></Doc_Title> <Doc_Url><![CDATA[finance.ifeng/stock/gsgg/20120321/5777632.shtml]]></Doc_Url>
</item>
</list>
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论