如何在BPM中使用REST服務(1):通過程式訪問網頁內容

李勝攀發表於2014-06-15

 

  這篇文章主要描述如何通過程式來訪問網頁內容,這是訪問REST服務的基礎。

  在Java中,我們可以使用HttpUrlConnection類來實現,程式碼如下。

  1 package http.base;
  2 
  3 import java.io.BufferedReader;
  4 import java.io.IOException;
  5 import java.io.InputStream;
  6 import java.io.InputStreamReader;
  7 import java.net.HttpURLConnection;
  8 import java.net.URL;
  9 import java.nio.charset.Charset;
 10 import java.util.Map;
 11 import java.util.Vector;
 12 
 13 
 14 public class HttpRequester {
 15     private String defaultContentEncoding;
 16  
 17     public HttpRequester() {
 18         this.defaultContentEncoding = Charset.defaultCharset().name();
 19     }
 20  
 21     public HttpResponse sendGet(String urlString) throws IOException {
 22         return this.send(urlString, "GET", null, null);
 23     }
 24  
 25     public HttpResponse sendGet(String urlString, Map<String, String> params)
 26             throws IOException {
 27         return this.send(urlString, "GET", params, null);
 28     }
 29  
 30     public HttpResponse sendGet(String urlString, Map<String, String> params,
 31             Map<String, String> propertys) throws IOException {
 32         return this.send(urlString, "GET", params, propertys);
 33     }
 34  
 35     public HttpResponse sendPost(String urlString) throws IOException {
 36         return this.send(urlString, "POST", null, null);
 37     }
 38  
 39     public HttpResponse sendPost(String urlString, Map<String, String> params)
 40             throws IOException {
 41         return this.send(urlString, "POST", params, null);
 42     }
 43  
 44     public HttpResponse sendPost(String urlString, Map<String, String> params,
 45             Map<String, String> propertys) throws IOException {
 46         return this.send(urlString, "POST", params, propertys);
 47     }
 48  
 49     private HttpResponse send(String urlString, String method,
 50             Map<String, String> parameters, Map<String, String> propertys)
 51             throws IOException {
 52         HttpURLConnection urlConnection = null;
 53  
 54         if (method.equalsIgnoreCase("GET") && parameters != null) {
 55             StringBuffer param = new StringBuffer();
 56             int i = 0;
 57             for (String key : parameters.keySet()) {
 58                 if (i == 0)
 59                     param.append("?");
 60                 else
 61                     param.append("&");
 62                 param.append(key).append("=").append(parameters.get(key));
 63                 i++;
 64             }
 65             urlString += param;
 66         }
 67         URL url = new URL(urlString);
 68         urlConnection = (HttpURLConnection) url.openConnection();
 69  
 70         urlConnection.setRequestMethod(method);
 71         urlConnection.setDoOutput(true);
 72         urlConnection.setDoInput(true);
 73         urlConnection.setUseCaches(false);
 74  
 75         if (propertys != null)
 76             for (String key : propertys.keySet()) {
 77                 urlConnection.addRequestProperty(key, propertys.get(key));
 78             }
 79  
 80         if (method.equalsIgnoreCase("POST") && parameters != null) {
 81             StringBuffer param = new StringBuffer();
 82             for (String key : parameters.keySet()) {
 83                 param.append("&");
 84                 param.append(key).append("=").append(parameters.get(key));
 85             }
 86             urlConnection.getOutputStream().write(param.toString().getBytes());
 87             urlConnection.getOutputStream().flush();
 88             urlConnection.getOutputStream().close();
 89         }
 90  
 91         return this.makeContent(urlString, urlConnection);
 92     }
 93  
 94     private HttpResponse makeContent(String urlString,
 95             HttpURLConnection urlConnection) throws IOException {
 96         HttpResponse httpResponser = new HttpResponse();
 97         try {
 98             InputStream in = urlConnection.getInputStream();
 99             BufferedReader bufferedReader = new BufferedReader(
100                     new InputStreamReader(in));
101             httpResponser.contentCollection = new Vector<String>();
102             StringBuffer temp = new StringBuffer();
103             String line = bufferedReader.readLine();
104             while (line != null) {
105                 httpResponser.contentCollection.add(line);
106                 temp.append(line).append("/r/n");
107                 line = bufferedReader.readLine();
108             }
109             bufferedReader.close();
110  
111             String ecod = urlConnection.getContentEncoding();
112             if (ecod == null)
113                 ecod = this.defaultContentEncoding;
114  
115             httpResponser.urlString = urlString;
116  
117             httpResponser.defaultPort = urlConnection.getURL().getDefaultPort();
118             httpResponser.file = urlConnection.getURL().getFile();
119             httpResponser.host = urlConnection.getURL().getHost();
120             httpResponser.path = urlConnection.getURL().getPath();
121             httpResponser.port = urlConnection.getURL().getPort();
122             httpResponser.protocol = urlConnection.getURL().getProtocol();
123             httpResponser.query = urlConnection.getURL().getQuery();
124             httpResponser.ref = urlConnection.getURL().getRef();
125             httpResponser.userInfo = urlConnection.getURL().getUserInfo();
126  
127             httpResponser.content = new String(temp.toString().getBytes(), ecod);
128             httpResponser.contentEncoding = ecod;
129             httpResponser.code = urlConnection.getResponseCode();
130             httpResponser.message = urlConnection.getResponseMessage();
131             httpResponser.contentType = urlConnection.getContentType();
132             httpResponser.method = urlConnection.getRequestMethod();
133             httpResponser.connectTimeout = urlConnection.getConnectTimeout();
134             httpResponser.readTimeout = urlConnection.getReadTimeout();
135  
136             return httpResponser;
137         } catch (IOException e) {
138             throw e;
139         } finally {
140             if (urlConnection != null)
141                 urlConnection.disconnect();
142         }
143     }
144  
145     public String getDefaultContentEncoding() {
146         return this.defaultContentEncoding;
147     }
148  
149     public void setDefaultContentEncoding(String defaultContentEncoding) {
150         this.defaultContentEncoding = defaultContentEncoding;
151     }
152 }
HttpRequest類
  1 package http.base;
  2 
  3 import java.util.Vector;
  4 
  5 public class HttpResponse {
  6  
  7     String urlString;
  8     int defaultPort;
  9     String file;
 10     String host;
 11     String path;
 12     int port;
 13     String protocol;
 14     String query;
 15     String ref;
 16     String userInfo;
 17     String contentEncoding;
 18     String content;
 19     String contentType;
 20     int code;
 21     String message;
 22     String method;
 23     int connectTimeout;
 24     int readTimeout;
 25     Vector<String> contentCollection;
 26     
 27     public String getContent() {
 28         return content;
 29     }
 30  
 31     public String getContentType() {
 32         return contentType;
 33     }
 34  
 35     public int getCode() {
 36         return code;
 37     }
 38  
 39     public String getMessage() {
 40         return message;
 41     }
 42  
 43     public Vector<String> getContentCollection() {
 44         return contentCollection;
 45     }
 46  
 47     public String getContentEncoding() {
 48         return contentEncoding;
 49     }
 50  
 51     public String getMethod() {
 52         return method;
 53     }
 54  
 55     public int getConnectTimeout() {
 56         return connectTimeout;
 57     }
 58  
 59     public int getReadTimeout() {
 60         return readTimeout;
 61     }
 62  
 63     public String getUrlString() {
 64         return urlString;
 65     }
 66  
 67     public int getDefaultPort() {
 68         return defaultPort;
 69     }
 70  
 71     public String getFile() {
 72         return file;
 73     }
 74  
 75     public String getHost() {
 76         return host;
 77     }
 78  
 79     public String getPath() {
 80         return path;
 81     }
 82  
 83     public int getPort() {
 84         return port;
 85     }
 86  
 87     public String getProtocol() {
 88         return protocol;
 89     }
 90  
 91     public String getQuery() {
 92         return query;
 93     }
 94  
 95     public String getRef() {
 96         return ref;
 97     }
 98  
 99     public String getUserInfo() {
100         return userInfo;
101     }
102  
103 }
HttpResponse類

  下面是一個簡單的測試類。

 1 package http.base;
 2 
 3 public class HttpTest {
 4     public static void main(String[] args) {
 5         try {
 6             HttpRequester request = new HttpRequester();
 7             HttpResponse hr = request.sendGet("http://www.baidu.com");            
 8  
 9             System.out.println(hr.getUrlString());
10             System.out.println(hr.getProtocol());
11             System.out.println(hr.getHost());
12             System.out.println(hr.getPort());
13             System.out.println(hr.getContentEncoding());
14             System.out.println(hr.getMethod());
15            
16             System.out.println(hr.getContent());
17  
18         } catch (Exception e) {
19             e.printStackTrace();
20         }
21     }
22 }
View Code

  因為REST服務的返回值一般都是JSON物件,下一篇文章中,我們來看Java物件和JSON之間如何轉換。

相關文章