1. 程式人生 > >API開發實踐(四) 返回HTML

API開發實踐(四) 返回HTML

acea 指定 win filename static box 拖動地圖 ive let

分為兩個部分:生成HTML和返回HTML

生成HTML:

最終想要的時顯示地圖,不可避免的使用高德地圖的API。

【地圖API】地址錄入時如何獲得準確的經緯度?淘寶收貨地址詳解

改變幾個參數即可達到目的,很簡單不講了。

重點說說如何生成查詢結果對應的HTML:

將HTML中的內容保存為String,在String格式的基礎上替換關鍵參數,即可批量生產。

在將HTML保存為String時,因為HTML內容都是帶換行縮進的,還帶有許多雙引號,所以直接粘貼實不可取的。

我用的方法是將內容先保存在文本中,再通過IO流讀取,並且一定要做到:

刪除所有換行符

將雙引號替換為單引號

將所有註釋都去掉

否則不滿足前兩條,String格式會報錯;

不滿足最後一條,輸出的時候因為沒有換行符,“//”又是行註釋,會導致把第一個“//”後的所有內容都認為是註釋而無法執行。

代碼:getHtml.java

 1 package util;
 2 
 3 import java.util.List;
 4 import java.util.regex.Pattern;
 5 
 6 public class getHtml {
 7     public getHtml(){}
 8     public String creatHtml(List<String> list){
 9         String html = null
; 10 String add = ""; 11 int j = list.size(); 12 for(int i = 1; i < j ; i++ ){ 13 if(i != j - 1){ 14 add = add + list.get(i) + "--->"; 15 }else{ 16 add = add + list.get(i);} 17 } 18 String address = list.get(j-1);
19 html = "<html> <head> <base href=‘<%=basePath%>‘> <meta http-equiv=‘pragma‘ content=‘no-cache‘> <meta http-equiv=‘cache-control‘ content=‘no-cache‘> <meta http-equiv=‘expires‘ content=‘0‘> <meta http-equiv=‘keywords‘ content=‘keyword1,keyword2,keyword3‘> <meta http-equiv=‘description‘ content=‘This is my page‘> <script type=‘text/javascript‘ src=‘http://webapi.amap.com/maps?v=1.3&key=0250860ccb5953fa5d655e8acf40ebb7&plugin=AMap.Geocoder‘></script> <script type=‘text/javascript‘ src=‘http://cache.amap.com/lbs/static/addToolbar.js‘></script> <style> #addressBox{height:20px;width:600px;} #mapBox{height:400px;width:600px} #pointBox{height:20px;width:600px;} </style> <!-- <link rel=‘stylesheet‘ type=‘text/css‘ href=‘styles.css‘> --> </head> <body onload=‘geocoder();‘> " 20 + " <p>物流軌跡:</p> " 21 + "<p>"+add+"</p>" 22 + "<div> <p>當前所在位置</p> </div> <div id=‘pointBox‘>&nbsp;</div> <div id=‘mapBox‘></div> <div> 如果不夠準確,可以拖動地圖改變經緯度 </div> " 23 + "<script type=‘text/javascript‘> var address =‘"+address 24 + "‘;var $pointBox = document.getElementById(‘pointBox‘); var map = new AMap.Map(‘mapBox‘, { resizeEnable: true, center: [116.397428, 39.90923], zoom:14 }); function addMarker(point) { var marker = new AMap.Marker({ map: map, position: [ point.getLng(), point.getLat()] }); } function addCenterPoint(){ map.clearMap(); var centerPoint = map.getCenter(); addMarker(centerPoint); $pointBox.innerHTML = ‘當前經緯度為:‘ + centerPoint.getLng() + ‘,‘ + centerPoint.getLat(); } addCenterPoint(); function geocoder() { map.clearMap(); var myGeo = new AMap.Geocoder(); myGeo.getLocation(address, function(status, result) { if (status === ‘complete‘ && result.info === ‘OK‘) { geocoder_CallBack(result); }else{ $pointBox.innerHTML = ‘查無此地址‘; } }); } function geocoder_CallBack(data) { var resultStr = ‘‘; var geocode = data.geocodes; addMarker(geocode[0].location); resultStr += ‘當前坐標</b>:‘ + geocode[0].location.getLng() + ‘, ‘ + geocode[0].location.getLat(); map.setFitView(); $pointBox.innerHTML = resultStr; } map.on(‘moveend‘, function() { addCenterPoint(); }); </script> </body></html>"; 25 String str = html.replaceAll( "\‘", "\""); 26 return str; 27 } 28 }

大家可以看到String html定義哪一行是如何處理更改參數和處理格式的。可以和最開始鏈接中的代碼進行對比。

返回HTML:

不說了,直接代碼:getMap.java

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        String shipperCode = request.getParameter("ShipperCode");
        String logisticCode = request.getParameter("LogisticCode");
        System.out.println(shipperCode+","+logisticCode);
        kdniaoTrackQueryAPI kdnAPI = new kdniaoTrackQueryAPI();
        List<String> result = kdnAPI.Return(shipperCode,logisticCode);
        String name = "";
        if(result.get(0).equals("0")){
            name = "<html><head><title>t.html</title></head><body>"+result.get(1)+"<br></body></html>";
        }else if(result.get(0).equals("1")){
            getHtml gH = new getHtml();
            name = gH.creatHtml(result);
        }else{
            name = "<html><head><title>t.html</title></head><body>"+result.get(1)+"<br></body></html>";
        }
               
        //返回文本數據  
        response.setContentType("text/plain;charset=UTF-8");  
        ServletOutputStream outputStream = response.getOutputStream();  
        outputStream.write(name.getBytes("UTF-8"));  
        outputStream.flush();  
        outputStream.close(); 
    }

隨便查查就有返回的方法

調用方法實例:

如何調用我的API

 1 package test;
 2 import java.io.BufferedReader;
 3 import java.io.File;
 4 import java.io.FileWriter;
 5 import java.io.IOException;
 6 import java.io.InputStreamReader;
 7 import java.io.OutputStreamWriter;
 8 import java.io.PrintWriter;
 9 import java.net.HttpURLConnection;
10 import java.net.URL;
11 import java.net.URLEncoder;
12 import java.util.Map;
13 
14 public class test1 {
15     public static void main(String args[]){
16         //請求url
17         String URL="安全起見,不可說,等我發布前端地址";
18         String ShipperCode = ""//物理公司編號;
19         String LogisticCode = ""//物流運單號;
20         String ReqURL = URL + "?ShipperCode=" + ShipperCode + "&LogisticCode=" + LogisticCode;
21         String result = sendPost(ReqURL);
22         write(result,"test");
23     } 
24      /**
25      * 向指定 URL 發送POST方法的請求          
26      * @return 遠程資源的響應結果
27      */
28     private static String sendPost(String url) {
29         OutputStreamWriter out = null;
30         BufferedReader in = null;        
31         StringBuilder result = new StringBuilder(); 
32         try {
33             URL realUrl = new URL(url);
34             HttpURLConnection conn =(HttpURLConnection) realUrl.openConnection();
35             // 發送POST請求必須設置如下兩行
36             conn.setDoOutput(true);
37             conn.setDoInput(true);
38             // POST方法
39             conn.setRequestMethod("POST");
40             // 設置通用的請求屬性
41             conn.setRequestProperty("accept", "*/*");
42             conn.setRequestProperty("connection", "Keep-Alive");
43             conn.setRequestProperty("user-agent",
44                     "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
45             conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
46             conn.setRequestProperty("kdniao-nocache", "true");
47             conn.connect();
48             // 獲取URLConnection對象對應的輸出流
49             out = new OutputStreamWriter(conn.getOutputStream(), "UTF-8");
50             // 定義BufferedReader輸入流來讀取URL的響應
51             in = new BufferedReader(
52                     new InputStreamReader(conn.getInputStream(), "UTF-8"));
53             String line;
54             while ((line = in.readLine()) != null) {
55                 result.append(line);
56             }
57         } catch (Exception e) {            
58             e.printStackTrace();
59         }
60         //使用finally塊來關閉輸出流、輸入流
61         finally{
62             try{
63                 if(out!=null){
64                     out.close();
65                 }
66                 if(in!=null){
67                     in.close();
68                 }
69             }
70             catch(IOException ex){
71                 ex.printStackTrace();
72             }
73         }
74         return result.toString();
75     }
76     /*@result 服務器返回的html
77      [email protected] 保存的文件名字 
78      * */
79     public static void write(String result,String fileName) {
80          FileWriter fw = null;
81          try {
82          //如果文件存在,則追加內容;如果文件不存在,則創建文件
83          File f=new File("E:\\"+fileName+".html");
84          fw = new FileWriter(f, true);
85          } catch (IOException e) {
86          e.printStackTrace();
87          }
88          PrintWriter pw = new PrintWriter(fw);
89          pw.print(result);
90          pw.flush();
91          try {
92          fw.flush();
93          pw.close();
94          fw.close();
95          } catch (IOException e) {
96          e.printStackTrace();
97          }
98          }
99 }

API開發實踐(四) 返回HTML