http協議 get/post 請求 解析XML


當你拿到一個接口文檔,要確定是協議接口。eg:HTTP協議 、WebService接口。

HTTP協議  URL為“http:”,這代表網頁使用的是HTTP協議。

Get請求

 // 根據地址獲取請        
     HttpGet get = new HttpGet(getUrl);//這里發送get// 獲取當前客戶端對象
     HttpClient httpClient = new DefaultHttpClient(); String status = null; // 請求返回狀態碼 String reason = null; // 返回原因 String exchangeResult = null; try { // 通過請求對象獲取響應對象 HttpResponse response = httpClient.execute(get); System.out.println("請求狀態碼:【" + response.getStatusLine().getStatusCode() + "】"); // 判斷網絡連接狀態碼是否正常(0--200都數正常) if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
          /**       
            
<result>    
              <Return Status="Success" Reason="" />
            </result>
  
            -- response.getEntity, 但當 exchangeResult 接收時為:<result>&ltReturn Status="Success" Reason="" /&gt</result> 
          **/
                exchangeResult = EntityUtils.toString(response.getEntity(),"utf-8");
                exchangeResult = exchangeResult.replaceAll("&lt;", "<").replaceAll("&gt;", ">"); // xml數據返回含有特殊字符,這里只考慮了 < 和 > 號
                Document doc = DocumentHelper.parseText(exchangeResult);  
                Element root = doc.getRootElement(); // Element DOM
                Iterator<Element> iter = root.elementIterator(); 
                while(iter.hasNext()){
                    Element tmpElement = (Element) iter.next(); // Return 節點
                    status = tmpElement.attributeValue("Status"); // Success
                    reason = tmpElement.attributeValue("Reason"); 
                }
                System.out.println("get獲取結果返回--status:【" + status + "】reason:【" +reason + "】");
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }

Post請求

  post請求一般用來推送數據,用多人會有疑問,要怎么樣構造自己想要的xml eg: ![CDATA[{字段值}]]

  

Element root = DocumentHelper.createElement("Root");
Element entity = root.addElement("Entity").addAttribute("EntityName", "book").addAttribute("remark", "false");
entity.addElement("Property").addAttribute("Name", "num").addCDATA("123");
String xmlInfo = "<?xml version='1.0' encoding='utf-8'?>" + root.asXML();

結果:
  <?xml version='1.0' encoding='utf-8'?>
    <Root>
       <Entity EntityName='book' remark='false' > 
        <Property Name='num'><![CDATA[123
]]></Property>
       </Entity>
    </Root>

 

     String data = postData.toString(); // xml 數據
        HttpClient httpclient = new HttpClient();
        PostMethod post = new PostMethod(postUrl);
        String exchangeResult = null;
        try {
            RequestEntity entity = new StringRequestEntity(data, "text/plain","utf-8");
            post.setRequestEntity(entity);
            httpclient.executeMethod(post); // post 請求 int code = post.getStatusCode();
            if (code == HttpStatus.SC_OK){
                
            }
        // 解析上同 exchangeResult
= new String(post.getResponseBodyAsString()); //接口返回的信息 exchangeResult = exchangeResult.replaceAll("&lt;", "<").replaceAll("&gt;", ">"); Document doc = DocumentHelper.parseText(exchangeResult); Element root = doc.getRootElement(); Iterator<Element> iter = root.elementIterator(); String status = null; String reason = null; while(iter.hasNext()){ Element tmpElement = (Element) iter.next(); status = tmpElement.attributeValue("Status"); reason = tmpElement.attributeValue("Reason"); } System.out.println("市接口推送過程數據結果:status:【" + status +"】,reason:【" + reason + "】"); } catch (Exception ex) { ex.printStackTrace(); } finally { post.releaseConnection(); }

有些人會有疑問為什么不轉為json來解析數據,但看我們紅色的xml數據,我們請求的時,返回的是String xml格式數據,但json強調的是 getString("Status") 返回一個text值,並不是參數屬性值。eg:<property name='status'>Success</property> ,

當這個情況時轉為json會取得status。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM