使用HttpClient 发送get、post请求,及其解析xml返回数据

时间:2022-06-08 18:40:31

一、关于HttpClient的使用:

可以参考这个博客地址,这里有详细的介绍,需要的可以先看一下:

地址是:http://blog.csdn.net/wangpeng047/article/details/19624529

二、项目中用到HttpClient 去请求一个地址,但是用get请求如果参数过多,不同的浏览器会导致不同程度的参数丢失,所以还应该要有post的请求的方式,在加上post请求方式的后,发现不能用原来解析get请求的方式来解析服务器返回的数据,经多方查找资料最终找到了解决方案,故记之;

代码如下:

 package com.shusheng.util;

 import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException; import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException; public class SendSmsMessage {
//验证用户信息
private static final String username = "username";
private static final String password = "password";
//字符编码及其他参数
private static final String charset = "utf-8";
private static final String url = "http://127.0.0.1:8080/WebAPI/dtest.actioin";
/*
* 因请求返回的数据中只需要code和result两个字段的信息,因此方法只返回一个存有这两个值的map
*/
//get方式请求
public static Map<String,String> sendMessageByGet(String content,String phones){
Map<String,String> map = new HashMap<String, String>();
HttpClient httpClient = new DefaultHttpClient();
String fullUrl = url + "?user="+username+"&pwd="+password+"&mobiles="+phones+"&contents="+content;
HttpGet httpGet = new HttpGet(fullUrl);
try {
HttpResponse response = httpClient.execute(httpGet);
HttpEntity entity = response.getEntity();
if (null != entity) {
InputStream in = entity.getContent();//将返回的内容流入输入流内
// 创建一个Document解析工厂
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
// 将输入流解析为Document
Document document = builder.parse(in);//用输入流实例化Document Element rootElement = document.getDocumentElement(); NodeList codeNode = rootElement.getElementsByTagName("Code");
map.put("Code", codeNode.item(0).getTextContent()); NodeList resultNode = rootElement.getElementsByTagName("Result");
map.put("Result", resultNode.item(0).getTextContent()); }
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (DOMException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ParserConfigurationException e) {
e.printStackTrace();
} catch (SAXException e) {
e.printStackTrace();
}
return map;
} //post方式请求
public static Map<String,String> sendMessageByPost(String content,String phones){
Map<String,String> map = new HashMap<String, String>();
// 创建默认的httpClient实例.
CloseableHttpClient httpclient = HttpClients.createDefault();
// 创建httppost
HttpPost httppost = new HttpPost(url);
// 创建参数队列
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("user", username));
formparams.add(new BasicNameValuePair("pwd", password));
formparams.add(new BasicNameValuePair("mobiles", phones));
formparams.add(new BasicNameValuePair("contents", content)); UrlEncodedFormEntity uefEntity;
try{
uefEntity = new UrlEncodedFormEntity(formparams, charset);
httppost.setEntity(uefEntity);
System.out.println("executing request " + httppost.getURI());
CloseableHttpResponse response = httpclient.execute(httppost);
try{
HttpEntity entity = response.getEntity();
if (entity != null) {
//将返回的数据直接转成String
String str = EntityUtils.toString(entity, "UTF-8") ;
System.out.println("--------------------------------------");
//注意这里不能写成EntityUtils.toString(entity, "UTF-8"),因为EntityUtils只能调用一次,否则会报错:java.io.IOException: Attempted read from closed stream
System.out.println("Response content: " + str);
System.out.println("--------------------------------------"); //这里用str作为参数获得 Document 对象
org.dom4j.Document document = DocumentHelper.parseText(str);
org.dom4j.Element rootElement = document.getRootElement(); String code = rootElement.element("Code").getText();
String result = rootElement.element("Result").getText();
map.put("Code", code);
map.put("Result", result);
}
}catch (DocumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
response.close();
} } catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
} return map ;
} //验证手机号方法
public static boolean checkPhoneNo(String phone){
if(phone==null || phone.trim().equals("")){
return false;
}
String regExp = "^[1]([3][0-9]{1}|59|58|88|89)[0-9]{8}$";
Pattern p = Pattern.compile(regExp);
Matcher m = p.matcher(phone);
return m.find();
} public static void main(String args[]){
//System.out.println(checkPhoneNo(null));
sendMessageByPost("【post请求】测试20151117_006","[正确手机号]");
}
}

这里贴一下服务器的返回String类型的xml数据:

 <?xml version="1.0" encoding="utf-8"?>
<APIResult xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
<Code>12270</Code>
<Result>短信提交成功</Result>
</APIResult>

三、以上代码也可以看做是用java解析返回类型为xml的数据的方法;通过inputstream或者String 创建Document对象,然后通过该对象来解析每个分支的数据;上面代码中,如果在pos方式请求方法里用get方法那种解析xml的方式(即使用InputStream)会报错:java.io.IOException: Attempted read from closed stream;因此才使用String来创建Document的方式解析post请求返回的xml数据。有需要可以自己测试下,反正是个单独的类调试非常方便。

以上内容来自工作中遇到的问题以及上网查询所得,记以温之。