View Javadoc

1   /*
2    * $id$
3    *
4    * copyright (c) 2005 patric fornasier, pawel kowalski
5    * all rights reserved.
6    */
7   package net.sf.orcus.sms.transport;
8   
9   import java.io.ByteArrayOutputStream;
10  import java.io.IOException;
11  import java.io.InputStream;
12  import java.io.OutputStream;
13  import java.net.URL;
14  import java.net.URLConnection;
15  
16  /***
17   * A transport handler for sending data via the HTTP protocol.
18   * 
19   * @version $Revision: 1.2 $, $Date: 2005/10/13 18:43:17 $
20   * @author Patric Fornasier
21   */
22  public class HttpTransportHandler implements TransportHandler {
23  
24      private String targetUrl;
25  
26      private String contentType;
27  
28      public byte[] invoke(byte[] data) throws TransportException {
29  
30          byte[] result = null;
31  
32          try {// open up new URLConnection
33              URL url = new URL(targetUrl);
34              URLConnection urlConn = url.openConnection();
35              if (contentType != null)
36                  urlConn.setRequestProperty("Content-Type", contentType);
37  
38              // set the connection to be used for input and output
39              urlConn.setDoOutput(true);
40              urlConn.setDoInput(true);
41  
42              // send off our data
43              OutputStream os = urlConn.getOutputStream();
44              os.write(data);
45              os.close();
46  
47              // get the response from the server
48              ByteArrayOutputStream baos = new ByteArrayOutputStream();
49              InputStream is = urlConn.getInputStream();
50              byte[] buf = new byte[1024];
51              int len;
52              while ((len = is.read(buf)) > 0) {
53                  baos.write(buf, 0, len);
54              }
55              is.close();
56              result = baos.toByteArray();
57              baos.close();
58  
59          } catch (IOException e) {
60              throw new TransportException("Unable to transport data to " + targetUrl, e);
61          }
62  
63          return result;
64      }
65  
66      /***
67       * Get the service endpoint url.
68       */
69      public String getTargetUrl() {
70          return targetUrl;
71      }
72  
73      /***
74       * Set the service endpoint url.
75       */
76      public void setTargetUrl(String targetUrl) {
77          this.targetUrl = targetUrl;
78      }
79  
80      /***
81       * Get the content type that will be used for this http request.
82       */
83      public String getContentType() {
84          return contentType;
85      }
86  
87      /***
88       * Set the content type that will be used for this http request.
89       */
90      public void setContentType(String contentType) {
91          this.contentType = contentType;
92      }
93  }