1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.springframework.extensions.webscripts.servlet;
20
21 import java.io.IOException;
22 import java.io.InputStream;
23 import java.io.OutputStream;
24 import java.net.HttpURLConnection;
25 import java.net.MalformedURLException;
26 import java.net.URL;
27 import java.net.URLConnection;
28
29 import javax.servlet.http.HttpServletResponse;
30
31
32
33
34
35
36
37 public class HTTPProxy
38 {
39 protected URL url;
40 protected HttpServletResponse response;
41
42
43
44
45
46
47
48
49
50 public HTTPProxy(String requestUrl, HttpServletResponse response)
51 throws MalformedURLException
52 {
53 this.url = new URL(requestUrl);
54 this.response = response;
55 }
56
57
58
59
60
61
62 public void service()
63 throws IOException
64 {
65 HttpURLConnection connection = (HttpURLConnection)url.openConnection();
66 initialiseResponse(connection);
67 InputStream input = connection.getInputStream();
68 OutputStream output = response.getOutputStream();
69 try
70 {
71 writeResponse(input, output);
72 }
73 finally
74 {
75 try
76 {
77 if (input != null)
78 {
79 input.close();
80 }
81 if (output != null)
82 {
83 output.flush();
84 output.close();
85 }
86
87 connection.disconnect();
88 }
89 catch(IOException e)
90 {
91
92 }
93 }
94 }
95
96
97
98
99
100
101 protected void initialiseResponse(URLConnection urlConnection)
102 {
103 String type = urlConnection.getContentType();
104 if (type != null)
105 {
106 int encodingIdx = type.lastIndexOf("charset=");
107 if (encodingIdx == -1)
108 {
109 String encoding = urlConnection.getContentEncoding();
110 if (encoding != null && encoding.length() > 0)
111 {
112 type += ";charset=" + encoding;
113 }
114 }
115
116 response.setContentType(type);
117 }
118 }
119
120
121
122
123
124
125
126
127 protected void writeResponse(InputStream input, OutputStream output)
128 throws IOException
129 {
130 byte[] buffer = new byte[4096];
131 int read = input.read(buffer);
132 while (read != -1)
133 {
134 output.write(buffer, 0, read);
135 read = input.read(buffer);
136 }
137 }
138 }