PageRenderTime 96ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/examples/9-VideoClientWithOauth2/src/org/magnum/videoup/client/unsafe/EasyHttpClient.java

https://gitlab.com/optlasuta/mobilecloud-14
Java | 326 lines | 197 code | 37 blank | 92 comment | 20 complexity | 7c2c4834170932d8e12164a8e9384751 MD5 | raw file
  1. /*
  2. **
  3. ** Copyright 2014, Jules White
  4. **
  5. **
  6. */
  7. package org.magnum.videoup.client.unsafe;
  8. /*
  9. * Licensed to the Apache Software Foundation (ASF) under one
  10. * or more contributor license agreements. See the NOTICE file
  11. * distributed with this work for additional information
  12. * regarding copyright ownership. The ASF licenses this file
  13. * to you under the Apache License, Version 2.0 (the
  14. * "License"); you may not use this file except in compliance
  15. * with the License. You may obtain a copy of the License at
  16. *
  17. * http://www.apache.org/licenses/LICENSE-2.0
  18. *
  19. * Unless required by applicable law or agreed to in writing,
  20. * software distributed under the License is distributed on an
  21. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22. * KIND, either express or implied. See the License for the
  23. * specific language governing permissions and limitations
  24. * under the License.
  25. */
  26. import java.io.ByteArrayOutputStream;
  27. import java.io.IOException;
  28. import java.io.InputStream;
  29. import java.net.InetAddress;
  30. import java.net.InetSocketAddress;
  31. import java.net.Socket;
  32. import java.net.UnknownHostException;
  33. import java.security.cert.CertificateException;
  34. import java.security.cert.X509Certificate;
  35. import java.util.zip.GZIPInputStream;
  36. import javax.net.ssl.SSLContext;
  37. import javax.net.ssl.SSLSocket;
  38. import javax.net.ssl.TrustManager;
  39. import javax.net.ssl.X509TrustManager;
  40. import org.apache.http.Header;
  41. import org.apache.http.HeaderElement;
  42. import org.apache.http.HttpEntity;
  43. import org.apache.http.HttpException;
  44. import org.apache.http.HttpRequest;
  45. import org.apache.http.HttpRequestInterceptor;
  46. import org.apache.http.HttpResponse;
  47. import org.apache.http.HttpResponseInterceptor;
  48. import org.apache.http.HttpVersion;
  49. import org.apache.http.auth.AuthScope;
  50. import org.apache.http.auth.UsernamePasswordCredentials;
  51. import org.apache.http.client.ClientProtocolException;
  52. import org.apache.http.client.methods.HttpGet;
  53. import org.apache.http.conn.ClientConnectionManager;
  54. import org.apache.http.conn.ConnectTimeoutException;
  55. import org.apache.http.conn.scheme.LayeredSocketFactory;
  56. import org.apache.http.conn.scheme.PlainSocketFactory;
  57. import org.apache.http.conn.scheme.Scheme;
  58. import org.apache.http.conn.scheme.SchemeRegistry;
  59. import org.apache.http.conn.scheme.SocketFactory;
  60. import org.apache.http.entity.HttpEntityWrapper;
  61. import org.apache.http.impl.client.BasicCredentialsProvider;
  62. import org.apache.http.impl.client.DefaultHttpClient;
  63. import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
  64. import org.apache.http.params.BasicHttpParams;
  65. import org.apache.http.params.HttpConnectionParams;
  66. import org.apache.http.params.HttpParams;
  67. import org.apache.http.params.HttpProtocolParams;
  68. import org.apache.http.protocol.HttpContext;
  69. /**
  70. * Easy to use Http and Https client, that transparently adds gzip compression
  71. * and ignores all Https certificates. It can also be used for using credentials
  72. * in your connection.
  73. *
  74. * This class was created for Android applications, where the appropriate apache libraries
  75. * are already available. If you are developing for another platform, make sure
  76. * to add the httpclient, httpcore and commons-logging libs to your buildpath.
  77. * They can be downloaded from http://hc.apache.org/downloads.cgi
  78. *
  79. * <code><br/>
  80. EasyHttpClient client = new EasyHttpClient();<br/>
  81. System.out.println(client.get("https://encrypted.google.com/"));<br/>
  82. * </code>
  83. *
  84. * @author match2blue software development GmbH
  85. * @author Ren� Fischer, Ulrich Scheller
  86. */
  87. public class EasyHttpClient extends DefaultHttpClient {
  88. /**
  89. * Default http port
  90. */
  91. private final static int HTTP_PORT = 80;
  92. /**
  93. * Default https port
  94. */
  95. private final static int HTTPS_PORT = 443;
  96. protected int lastStatusCode;
  97. protected String lastReasonPhrase;
  98. /**
  99. * Default constructor that initializes gzip handling. It adds the
  100. * Accept-Encoding gzip flag and also decompresses the response from the server.
  101. */
  102. public EasyHttpClient() {
  103. addRequestInterceptor(new HttpRequestInterceptor() {
  104. public void process(final HttpRequest request,
  105. final HttpContext context) throws HttpException, IOException {
  106. if (!request.containsHeader("Accept-Encoding")) {
  107. request.addHeader("Accept-Encoding", "gzip");
  108. }
  109. }
  110. });
  111. addResponseInterceptor(new HttpResponseInterceptor() {
  112. public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException {
  113. HttpEntity entity = response.getEntity();
  114. Header ceheader = entity.getContentEncoding();
  115. if (ceheader != null) {
  116. for (HeaderElement headerElement : ceheader.getElements()) {
  117. if (headerElement.getName().equalsIgnoreCase("gzip")) {
  118. response.setEntity(new GzipEntityWrapper(response.getEntity()));
  119. lastStatusCode = response.getStatusLine().getStatusCode();
  120. lastReasonPhrase = response.getStatusLine().getReasonPhrase();
  121. return;
  122. }
  123. }
  124. }
  125. }
  126. });
  127. }
  128. /**
  129. * Constructor which handles credentials for the connection (only if username and password are set)
  130. *
  131. * @param username
  132. * @param password
  133. */
  134. public EasyHttpClient(String username, String password) {
  135. if(username != null && password != null) {
  136. UsernamePasswordCredentials c = new UsernamePasswordCredentials(username,password);
  137. BasicCredentialsProvider cP = new BasicCredentialsProvider();
  138. cP.setCredentials(AuthScope.ANY, c);
  139. setCredentialsProvider(cP);
  140. }
  141. }
  142. /**
  143. * Function that creates a ClientConnectionManager which can handle http and https.
  144. * In case of https self signed or invalid certificates will be accepted.
  145. */
  146. @Override
  147. protected ClientConnectionManager createClientConnectionManager() {
  148. HttpParams params = new BasicHttpParams();
  149. HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
  150. HttpProtocolParams.setContentCharset(params, "utf-8");
  151. params.setBooleanParameter("http.protocol.expect-continue", false);
  152. SchemeRegistry registry = new SchemeRegistry();
  153. registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), HTTP_PORT));
  154. registry.register(new Scheme("https", new EasySSLSocketFactory(), HTTPS_PORT));
  155. ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(params, registry);
  156. return manager;
  157. }
  158. /**
  159. * Make a get request to the specified url
  160. * @param url
  161. * @return the response string, null if there was an error
  162. */
  163. public String get(String url) {
  164. HttpGet getReq = new HttpGet(url);
  165. InputStream content = null;
  166. try {
  167. content = execute(getReq).getEntity().getContent();
  168. ByteArrayOutputStream bout = new ByteArrayOutputStream();
  169. byte[] buf = new byte[1024];
  170. int len;
  171. while ((len = content.read(buf)) > 0) {
  172. bout.write(buf, 0, len);
  173. }
  174. content.close();
  175. return bout.toString();
  176. } catch (IllegalStateException e) {
  177. e.printStackTrace();
  178. } catch (ClientProtocolException e) {
  179. e.printStackTrace();
  180. } catch (IOException e) {
  181. e.printStackTrace();
  182. }
  183. return null;
  184. }
  185. public static void main(String[] args) {
  186. EasyHttpClient client = new EasyHttpClient();
  187. System.out.println(client.get("https://encrypted.google.com/"));
  188. }
  189. }
  190. class GzipEntityWrapper extends HttpEntityWrapper {
  191. public GzipEntityWrapper(HttpEntity wrapped) {
  192. super(wrapped);
  193. }
  194. @Override
  195. public InputStream getContent() throws IOException, IllegalStateException {
  196. return new GZIPInputStream(wrappedEntity.getContent());
  197. }
  198. }
  199. /**
  200. * This socket factory will create ssl socket that accepts self signed
  201. * certificate
  202. */
  203. class EasySSLSocketFactory implements SocketFactory, LayeredSocketFactory {
  204. private SSLContext sslcontext = null;
  205. private static SSLContext createEasySSLContext() throws IOException {
  206. try {
  207. SSLContext context = SSLContext.getInstance("TLS");
  208. context.init(null,
  209. new TrustManager[] { new TrivialTrustManager() }, null);
  210. return context;
  211. } catch (Exception e) {
  212. throw new IOException(e.getMessage());
  213. }
  214. }
  215. private SSLContext getSSLContext() throws IOException {
  216. if (this.sslcontext == null) {
  217. this.sslcontext = createEasySSLContext();
  218. }
  219. return this.sslcontext;
  220. }
  221. /**
  222. * @see org.apache.http.conn.scheme.SocketFactory#connectSocket(java.net.Socket,
  223. * java.lang.String, int, java.net.InetAddress, int,
  224. * org.apache.http.params.HttpParams)
  225. */
  226. public Socket connectSocket(Socket sock, String host, int port,
  227. InetAddress localAddress, int localPort, HttpParams params)
  228. throws IOException, UnknownHostException, ConnectTimeoutException {
  229. int connTimeout = HttpConnectionParams.getConnectionTimeout(params);
  230. int soTimeout = HttpConnectionParams.getSoTimeout(params);
  231. InetSocketAddress remoteAddress = new InetSocketAddress(host, port);
  232. SSLSocket sslsock = (SSLSocket) ((sock != null) ? sock : createSocket());
  233. if ((localAddress != null) || (localPort > 0)) {
  234. // we need to bind explicitly
  235. if (localPort < 0) {
  236. localPort = 0; // indicates "any"
  237. }
  238. InetSocketAddress isa = new InetSocketAddress(localAddress,
  239. localPort);
  240. sslsock.bind(isa);
  241. }
  242. sslsock.connect(remoteAddress, connTimeout);
  243. sslsock.setSoTimeout(soTimeout);
  244. return sslsock;
  245. }
  246. /**
  247. * @see org.apache.http.conn.scheme.SocketFactory#createSocket()
  248. */
  249. public Socket createSocket() throws IOException {
  250. return getSSLContext().getSocketFactory().createSocket();
  251. }
  252. /**
  253. * @see org.apache.http.conn.scheme.SocketFactory#isSecure(java.net.Socket)
  254. */
  255. public boolean isSecure(Socket socket) throws IllegalArgumentException {
  256. return true;
  257. }
  258. /**
  259. * @see org.apache.http.conn.scheme.LayeredSocketFactory#createSocket(java.net.Socket,
  260. * java.lang.String, int, boolean)
  261. */
  262. public Socket createSocket(Socket socket, String host, int port,
  263. boolean autoClose) throws IOException, UnknownHostException {
  264. return getSSLContext().getSocketFactory().createSocket(socket, host,
  265. port, autoClose);
  266. }
  267. // -------------------------------------------------------------------
  268. // javadoc in org.apache.http.conn.scheme.SocketFactory says :
  269. // Both Object.equals() and Object.hashCode() must be overridden
  270. // for the correct operation of some connection managers
  271. // -------------------------------------------------------------------
  272. public boolean equals(Object obj) {
  273. return ((obj != null) && obj.getClass() == this.getClass());
  274. }
  275. public int hashCode() {
  276. return EasySSLSocketFactory.class.hashCode();
  277. }
  278. }
  279. class TrivialTrustManager implements X509TrustManager {
  280. public void checkClientTrusted(X509Certificate[] chain, String authType)
  281. throws CertificateException {
  282. }
  283. public void checkServerTrusted(X509Certificate[] chain, String authType)
  284. throws CertificateException {
  285. }
  286. public X509Certificate[] getAcceptedIssuers() {
  287. return new X509Certificate[0];
  288. }
  289. }