一、關於HttpClient的使用:
可以參考這個博客地址,這里有詳細的介紹,需要的可以先看一下:
地址是:http://blog.csdn.net/wangpeng047/article/details/19624529
二、項目中用到HttpClient 去請求一個地址,但是用get請求如果參數過多,不同的瀏覽器會導致不同程度的參數丟失,所以還應該要有post的請求的方式,在加上post請求方式的后,發現不能用原來解析get請求的方式來解析服務器返回的數據,經多方查找資料最終找到了解決方案,故記之;
代碼如下:
1 package com.shusheng.util; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.io.UnsupportedEncodingException; 6 import java.util.ArrayList; 7 import java.util.HashMap; 8 import java.util.List; 9 import java.util.Map; 10 import java.util.regex.Matcher; 11 import java.util.regex.Pattern; 12 13 import javax.xml.parsers.DocumentBuilder; 14 import javax.xml.parsers.DocumentBuilderFactory; 15 import javax.xml.parsers.ParserConfigurationException; 16 17 18 import org.apache.http.HttpEntity; 19 import org.apache.http.HttpResponse; 20 import org.apache.http.NameValuePair; 21 import org.apache.http.client.ClientProtocolException; 22 import org.apache.http.client.HttpClient; 23 import org.apache.http.client.entity.UrlEncodedFormEntity; 24 import org.apache.http.client.methods.CloseableHttpResponse; 25 import org.apache.http.client.methods.HttpGet; 26 import org.apache.http.client.methods.HttpPost; 27 import org.apache.http.impl.client.CloseableHttpClient; 28 import org.apache.http.impl.client.DefaultHttpClient; 29 import org.apache.http.impl.client.HttpClients; 30 import org.apache.http.message.BasicNameValuePair; 31 import org.apache.http.util.EntityUtils; 32 import org.dom4j.DocumentException; 33 import org.dom4j.DocumentHelper; 34 import org.w3c.dom.DOMException; 35 import org.w3c.dom.Document; 36 import org.w3c.dom.Element; 37 import org.w3c.dom.NodeList; 38 import org.xml.sax.SAXException; 39 40 public class SendSmsMessage { 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兩個字段的信息,因此方法只返回一個存有這兩個值的map 49 */ 50 //get方式請求 51 public static Map<String,String> sendMessageByGet(String content,String phones){ 52 Map<String,String> map = new HashMap<String, String>(); 53 HttpClient httpClient = new DefaultHttpClient(); 54 String fullUrl = url + "?user="+username+"&pwd="+password+"&mobiles="+phones+"&contents="+content; 55 HttpGet httpGet = new HttpGet(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 return map; 90 } 91 92 //post方式請求 93 public static Map<String,String> sendMessageByPost(String content,String phones){ 94 Map<String,String> map = new HashMap<String, String>(); 95 // 創建默認的httpClient實例. 96 CloseableHttpClient httpclient = HttpClients.createDefault(); 97 // 創建httppost 98 HttpPost httppost = new HttpPost(url); 99 // 創建參數隊列 100 List<NameValuePair> formparams = new ArrayList<NameValuePair>(); 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 = new UrlEncodedFormEntity(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 return map ; 154 } 155 156 //驗證手機號方法 157 public static boolean checkPhoneNo(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 return m.find(); 165 } 166 167 public static void main(String args[]){ 168 //System.out.println(checkPhoneNo(null)); 169 sendMessageByPost("【post請求】測試20151117_006","[正確手機號]"); 170 } 171 }
這里貼一下服務器的返回String類型的xml數據:
1 <?xml version="1.0" encoding="utf-8"?> 2 <APIResult xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/"> 3 <Code>12270</Code> 4 <Result>短信提交成功</Result> 5 </APIResult>
三、以上代碼也可以看做是用java解析返回類型為xml的數據的方法;通過inputstream或者String 創建Document對象,然后通過該對象來解析每個分支的數據;上面代碼中,如果在pos方式請求方法里用get方法那種解析xml的方式(即使用InputStream)會報錯:java.io.IOException: Attempted read from closed stream;因此才使用String來創建Document的方式解析post請求返回的xml數據。有需要可以自己測試下,反正是個單獨的類調試非常方便。
以上內容來自工作中遇到的問題以及上網查詢所得,記以溫之。