View Javadoc

1   /*
2    * Copyright (c) 2012, Maximilian Schmidt
3    * All rights reserved.
4    *
5    * Redistribution and use in source and binary forms, with or without modification,
6    * are permitted provided that the following conditions are met:
7    * 
8    * Redistributions of source code must retain the above copyright notice, this 
9    * list of conditions and the following disclaimer.
10   * Redistributions in binary form must reproduce the above copyright notice, 
11   * this list of conditions and the following disclaimer in the documentation 
12   * and/or other materials provided with the distribution.
13   * 
14   * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
15   * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
16   * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 
17   * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 
18   * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 
19   * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 
20   * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 
21   * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 
22   * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
23   * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24   * 
25   */
26  package de.fub.mi.idenpa.httpclient;
27  
28  import java.io.BufferedReader;
29  import java.io.ByteArrayInputStream;
30  import java.io.IOException;
31  import java.io.InputStream;
32  import java.io.InputStreamReader;
33  import java.net.URL;
34  import java.security.SecureRandom;
35  import java.security.cert.X509Certificate;
36  
37  import javax.net.ssl.SSLContext;
38  import javax.net.ssl.SSLException;
39  import javax.net.ssl.SSLSession;
40  import javax.net.ssl.SSLSocket;
41  import javax.net.ssl.TrustManager;
42  import javax.net.ssl.X509TrustManager;
43  
44  import org.apache.http.HttpResponse;
45  import org.apache.http.client.HttpClient;
46  import org.apache.http.client.methods.HttpGet;
47  import org.apache.http.client.methods.HttpPost;
48  import org.apache.http.client.methods.HttpUriRequest;
49  import org.apache.http.client.params.ClientPNames;
50  import org.apache.http.conn.ClientConnectionManager;
51  import org.apache.http.conn.scheme.Scheme;
52  import org.apache.http.conn.scheme.SchemeRegistry;
53  import org.apache.http.conn.ssl.AbstractVerifier;
54  import org.apache.http.conn.ssl.SSLSocketFactory;
55  import org.apache.http.conn.ssl.X509HostnameVerifier;
56  import org.apache.http.entity.StringEntity;
57  import org.apache.http.impl.client.DefaultHttpClient;
58  import org.apache.http.impl.conn.SingleClientConnManager;
59  import org.apache.http.params.BasicHttpParams;
60  import org.apache.http.params.HttpParams;
61  import org.slf4j.Logger;
62  import org.slf4j.LoggerFactory;
63  
64  /**
65   * Provides HTTP(S)-client functionality based of Apache's HttpClient, allowing SSL connections with unknown server certificates
66   */
67  public class HTTPClient {
68  
69  	/** The Constant m_objLog. */
70  	public static final Logger m_objLog = LoggerFactory.getLogger(HTTPClient.class);
71  	
72  	/** The m_obj client. */
73  	private HttpClient m_objClient;
74  	
75  	/** The m_obj req. */
76  	private HttpUriRequest m_objReq;
77  	
78  	/** The m_obj resp. */
79  	private HttpResponse m_objResp;
80  
81  	/**
82  	 * Instantiates a new hTTP client.
83  	 */
84  	public HTTPClient() {
85  		m_objClient = getTolerantClient();
86  	}
87  
88  	/**
89  	 * Gets the tolerant client.
90  	 *
91  	 * @return the tolerant client
92  	 */
93  	private DefaultHttpClient getTolerantClient() {
94  		DefaultHttpClient result = null;
95  
96  		try {
97  			SSLContext sslContext = SSLContext.getInstance("SSL");
98  
99  			// set up a TrustManager that trusts everything
100 			sslContext.init(null, new TrustManager[] { new X509TrustManager() {
101 				public X509Certificate[] getAcceptedIssuers() {
102 					System.out.println("getAcceptedIssuers =============");
103 					return null;
104 				}
105 
106 				public void checkClientTrusted(X509Certificate[] certs,
107 						String authType) {
108 					System.out.println("checkClientTrusted =============");
109 				}
110 
111 				public void checkServerTrusted(X509Certificate[] certs,
112 						String authType) {
113 					System.out.println("checkServerTrusted =============");
114 				}
115 			} }, new SecureRandom());
116 
117 			SSLSocketFactory sf = new SSLSocketFactory(sslContext);
118 			sf.setHostnameVerifier(new X509HostnameVerifier() {
119 				
120 				@Override
121 				public boolean verify(String arg0, SSLSession arg1) {
122 					// TODO Auto-generated method stub
123 					return true;
124 				}
125 				
126 				@Override
127 				public void verify(String arg0, String[] arg1, String[] arg2)
128 						throws SSLException {
129 					// TODO Auto-generated method stub
130 					
131 				}
132 				
133 				@Override
134 				public void verify(String arg0, X509Certificate arg1) throws SSLException {
135 					// TODO Auto-generated method stub
136 					
137 				}
138 				
139 				@Override
140 				public void verify(String arg0, SSLSocket arg1) throws IOException {
141 					// TODO Auto-generated method stub
142 					
143 				}
144 			});
145 			Scheme httpsScheme = new Scheme("https", sf, 443);
146 			SchemeRegistry schemeRegistry = new SchemeRegistry();
147 			schemeRegistry.register(httpsScheme);
148 
149 			HttpParams params = new BasicHttpParams();
150 			ClientConnectionManager cm = new SingleClientConnManager(params,
151 					schemeRegistry);
152 			result = new DefaultHttpClient(cm, params);
153 		} catch (Throwable t) {
154 			t.printStackTrace();
155 		}
156 		return result;
157 	}
158 
159 	/**
160 	 * Gets the.
161 	 *
162 	 * @param url the url
163 	 * @return the string
164 	 */
165 	public String get(URL url) {
166 		String result = null;
167 
168 		try {
169 			m_objReq = new HttpGet(url.toString());
170 			HttpParams params = m_objReq.getParams();
171 			params.setParameter(ClientPNames.HANDLE_REDIRECTS, Boolean.FALSE);
172 			m_objReq.setParams(params);
173 			m_objResp = m_objClient.execute(m_objReq);
174 			result = toString(m_objResp);
175 		} catch (Exception e) {
176 			e.printStackTrace();
177 		}
178 
179 		return result;
180 	}
181 
182 	/**
183 	 * Post to str.
184 	 *
185 	 * @param url the url
186 	 * @param content the content
187 	 * @return the string
188 	 */
189 	public String postToStr(String url, String content) {
190 		String result = null;
191 
192 		try {
193 			m_objReq = new HttpPost(url);
194 			((HttpPost) m_objReq).setEntity(new StringEntity(content, "UTF-8"));
195 			m_objResp = m_objClient.execute(m_objReq);
196 			result = toString(m_objResp);
197 		} catch (Exception e) {
198 			e.printStackTrace();
199 		}
200 
201 		return result;
202 	}
203 	
204 	/**
205 	 * Post.
206 	 *
207 	 * @param url the url
208 	 * @param content the content
209 	 * @return the input stream
210 	 */
211 	public InputStream post(String url, String content) {
212 		InputStream result = null;
213 
214 		try {
215 			m_objReq = new HttpPost(url);
216 			((HttpPost) m_objReq).setEntity(new StringEntity(content, "UTF-8"));
217 			m_objResp = m_objClient.execute(m_objReq);
218 			String strResp = toString(m_objResp);
219 			m_objLog.info("Got HTTP response with content: "+strResp);
220 			result = new ByteArrayInputStream(strResp.getBytes());
221 			//result = m_objResp.getEntity().getContent();
222 		} catch (Exception e) {
223 			e.printStackTrace();
224 		}
225 
226 		return result;
227 	}
228 
229 	/**
230 	 * To string.
231 	 *
232 	 * @param resp the resp
233 	 * @return the string
234 	 * @throws IOException Signals that an I/O exception has occurred.
235 	 */
236 	private String toString(HttpResponse resp) throws IOException {
237 		String result = null;
238 
239 		if (resp != null && resp.getEntity() != null) {
240 			InputStream in = resp.getEntity().getContent();
241 			BufferedReader reader = new BufferedReader(
242 					new InputStreamReader(in));
243 			String line = null;
244 			StringBuffer buffer = new StringBuffer();
245 			while ((line = reader.readLine()) != null) {
246 				buffer.append(line).append("\n");
247 			}
248 			result = buffer.toString();
249 		}
250 
251 		return result;
252 	}
253 
254 	/**
255 	 * The Class MyVerifier.
256 	 */
257 	class MyVerifier extends AbstractVerifier {
258 
259 		/** The delegate. */
260 		private final X509HostnameVerifier delegate;
261 
262 		/**
263 		 * Instantiates a new my verifier.
264 		 *
265 		 * @param delegate the delegate
266 		 */
267 		public MyVerifier(final X509HostnameVerifier delegate) {
268 			this.delegate = delegate;
269 		}
270 
271 		/* (non-Javadoc)
272 		 * @see org.apache.http.conn.ssl.X509HostnameVerifier#verify(java.lang.String, java.lang.String[], java.lang.String[])
273 		 */
274 		@Override
275 		public void verify(String host, String[] cns, String[] subjectAlts)
276 				throws SSLException {
277 			/*
278 			 * boolean ok = false; try { delegate.verify(host, cns,
279 			 * subjectAlts); } catch (SSLException e) { for (String cn : cns) {
280 			 * if (cn.startsWith("*.")) { try { delegate.verify(host, new
281 			 * String[] { cn.substring(2) }, subjectAlts); ok = true; } catch
282 			 * (Exception e1) { } } } if(!ok) throw e; }
283 			 */
284 		}
285 	}
286 }