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

沈开畅
2023-12-01

1 packagecom.shusheng.util;2

3 importjava.io.IOException;4 importjava.io.InputStream;5 importjava.io.UnsupportedEncodingException;6 importjava.util.ArrayList;7 importjava.util.HashMap;8 importjava.util.List;9 importjava.util.Map;10 importjava.util.regex.Matcher;11 importjava.util.regex.Pattern;12

13 importjavax.xml.parsers.DocumentBuilder;14 importjavax.xml.parsers.DocumentBuilderFactory;15 importjavax.xml.parsers.ParserConfigurationException;16

17

18 importorg.apache.http.HttpEntity;19 importorg.apache.http.HttpResponse;20 importorg.apache.http.NameValuePair;21 importorg.apache.http.client.ClientProtocolException;22 importorg.apache.http.client.HttpClient;23 importorg.apache.http.client.entity.UrlEncodedFormEntity;24 importorg.apache.http.client.methods.CloseableHttpResponse;25 importorg.apache.http.client.methods.HttpGet;26 importorg.apache.http.client.methods.HttpPost;27 importorg.apache.http.impl.client.CloseableHttpClient;28 importorg.apache.http.impl.client.DefaultHttpClient;29 importorg.apache.http.impl.client.HttpClients;30 importorg.apache.http.message.BasicNameValuePair;31 importorg.apache.http.util.EntityUtils;32 importorg.dom4j.DocumentException;33 importorg.dom4j.DocumentHelper;34 importorg.w3c.dom.DOMException;35 importorg.w3c.dom.Document;36 importorg.w3c.dom.Element;37 importorg.w3c.dom.NodeList;38 importorg.xml.sax.SAXException;39

40 public classSendSmsMessage {41 //验证用户信息

42 private static final String username = "username";43 private static final String password = "password";44 //字符编码及其他参数

45 private static final String charset = "utf-8";46 private static final String url = "http://127.0.0.1:8080/WebAPI/dtest.actioin";47 /*

48 * 因请求返回的数据中只需要code和result两个字段的信息,因此方法只返回一个存有这两个值的map49 */

50 //get方式请求

51 public static MapsendMessageByGet(String content,String phones){52 Map map = new HashMap();53 HttpClient httpClient = newDefaultHttpClient();54 String fullUrl = url + "?user="+username+"&pwd="+password+"&mobiles="+phones+"&contents="+content;55 HttpGet httpGet = newHttpGet(fullUrl);56 try{57 HttpResponse response =httpClient.execute(httpGet);58 HttpEntity entity =response.getEntity();59 if (null !=entity) {60 InputStream in = entity.getContent();//将返回的内容流入输入流内61 //创建一个Document解析工厂

62 DocumentBuilderFactory factory =DocumentBuilderFactory.newInstance();63 DocumentBuilder builder =factory.newDocumentBuilder();64 //将输入流解析为Document

65 Document document = builder.parse(in);//用输入流实例化Document

66

67 Element rootElement =document.getDocumentElement();68

69 NodeList codeNode = rootElement.getElementsByTagName("Code");70 map.put("Code", codeNode.item(0).getTextContent());71

72 NodeList resultNode = rootElement.getElementsByTagName("Result");73 map.put("Result", resultNode.item(0).getTextContent());74

75 }76 } catch(ClientProtocolException e) {77 e.printStackTrace();78 } catch(IllegalStateException e) {79 e.printStackTrace();80 } catch(DOMException e) {81 e.printStackTrace();82 } catch(IOException e) {83 e.printStackTrace();84 } catch(ParserConfigurationException e) {85 e.printStackTrace();86 } catch(SAXException e) {87 e.printStackTrace();88 }89 returnmap;90 }91

92 //post方式请求

93 public static MapsendMessageByPost(String content,String phones){94 Map map = new HashMap();95 //创建默认的httpClient实例.

96 CloseableHttpClient httpclient =HttpClients.createDefault();97 //创建httppost

98 HttpPost httppost = newHttpPost(url);99 //创建参数队列

100 List formparams = new ArrayList();101 formparams.add(new BasicNameValuePair("user", username));102 formparams.add(new BasicNameValuePair("pwd", password));103 formparams.add(new BasicNameValuePair("mobiles", phones));104 formparams.add(new BasicNameValuePair("contents", content));105

106 UrlEncodedFormEntity uefEntity;107 try{108 uefEntity = newUrlEncodedFormEntity(formparams, charset);109 httppost.setEntity(uefEntity);110 System.out.println("executing request " +httppost.getURI());111 CloseableHttpResponse response =httpclient.execute(httppost);112 try{113 HttpEntity entity =response.getEntity();114 if (entity != null) {115 //将返回的数据直接转成String

116 String str = EntityUtils.toString(entity, "UTF-8") ;117 System.out.println("--------------------------------------");118 //注意这里不能写成EntityUtils.toString(entity, "UTF-8"),因为EntityUtils只能调用一次,否则会报错:java.io.IOException: Attempted read from closed stream

119 System.out.println("Response content: " +str);120 System.out.println("--------------------------------------");121

122 //这里用str作为参数获得 Document 对象

123 org.dom4j.Document document =DocumentHelper.parseText(str);124 org.dom4j.Element rootElement =document.getRootElement();125

126 String code = rootElement.element("Code").getText();127 String result = rootElement.element("Result").getText();128 map.put("Code", code);129 map.put("Result", result);130 }131 }catch(DocumentException e) {132 //TODO Auto-generated catch block

133 e.printStackTrace();134 }finally{135 response.close();136 }137

138 } catch(ClientProtocolException e) {139 e.printStackTrace();140 } catch(UnsupportedEncodingException e1) {141 e1.printStackTrace();142 } catch(IOException e) {143 e.printStackTrace();144 }finally{145 //关闭连接,释放资源

146 try{147 httpclient.close();148 } catch(IOException e) {149 e.printStackTrace();150 }151 }152

153 returnmap ;154 }155

156 //验证手机号方法

157 public static booleancheckPhoneNo(String phone){158 if(phone==null || phone.trim().equals("")){159 return false;160 }161 String regExp = "^[1]([3][0-9]{1}|59|58|88|89)[0-9]{8}$";162 Pattern p =Pattern.compile(regExp);163 Matcher m =p.matcher(phone);164 returnm.find();165 }166

167 public static voidmain(String args[]){168 //System.out.println(checkPhoneNo(null));

169 sendMessageByPost("【post请求】测试20151117_006","[正确手机号]");170 }171 }

 类似资料: