Advertisement
patryk4815

Untitled

Aug 1st, 2015
295
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 11.92 KB | None | 0 0
  1. /*
  2. * Copyright (c) 2010 - 2015 Ushahidi Inc
  3. * All rights reserved
  4. * Contact: team@ushahidi.com
  5. * Website: http://www.ushahidi.com
  6. * GNU Lesser General Public License Usage
  7. * This file may be used under the terms of the GNU Lesser
  8. * General Public License version 3 as published by the Free Software
  9. * Foundation and appearing in the file LICENSE.LGPL included in the
  10. * packaging of this file. Please review the following information to
  11. * ensure the GNU Lesser General Public License version 3 requirements
  12. * will be met: http://www.gnu.org/licenses/lgpl.html.
  13. *
  14. * If you have questions regarding the use of this file, please contact
  15. * Ushahidi developers at team@ushahidi.com.
  16. */
  17.  
  18. package org.addhen.smssync.net;
  19.  
  20. import org.addhen.smssync.net.ssl.TrustedSocketFactory;
  21. import org.addhen.smssync.util.Logger;
  22. import org.apache.http.HttpEntity;
  23. import org.apache.http.HttpResponse;
  24. import org.apache.http.HttpVersion;
  25. import org.apache.http.NameValuePair;
  26. import org.apache.http.client.ClientProtocolException;
  27. import org.apache.http.client.entity.UrlEncodedFormEntity;
  28. import org.apache.http.client.methods.HttpGet;
  29. import org.apache.http.client.methods.HttpPost;
  30. import org.apache.http.client.methods.HttpPut;
  31. import org.apache.http.client.methods.HttpRequestBase;
  32. import org.apache.http.conn.params.ConnManagerPNames;
  33. import org.apache.http.conn.params.ConnPerRouteBean;
  34. import org.apache.http.conn.scheme.PlainSocketFactory;
  35. import org.apache.http.conn.scheme.Scheme;
  36. import org.apache.http.conn.scheme.SchemeRegistry;
  37. import org.apache.http.entity.StringEntity;
  38. import org.apache.http.impl.client.DefaultHttpClient;
  39. import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
  40. import org.apache.http.message.BasicNameValuePair;
  41. import org.apache.http.params.BasicHttpParams;
  42. import org.apache.http.params.HttpConnectionParams;
  43. import org.apache.http.params.HttpParams;
  44. import org.apache.http.params.HttpProtocolParams;
  45.  
  46. import android.content.Context;
  47. import android.content.pm.PackageManager.NameNotFoundException;
  48. import android.util.Base64;
  49.  
  50. import java.io.BufferedReader;
  51. import java.io.IOException;
  52. import java.io.InputStream;
  53. import java.io.InputStreamReader;
  54. import java.net.URI;
  55. import java.net.URISyntaxException;
  56. import java.net.URLEncoder;
  57. import java.nio.charset.Charset;
  58. import java.security.KeyManagementException;
  59. import java.security.NoSuchAlgorithmException;
  60. import java.util.ArrayList;
  61. import java.util.HashMap;
  62. import java.util.Map;
  63.  
  64.  
  65. public abstract class BaseHttpClient {
  66.  
  67. private static final String DEFAULT_ENCODING = "UTF-8";
  68.  
  69. private static final String CLASS_TAG = MainHttpClient.class.getSimpleName();
  70.  
  71. protected static DefaultHttpClient httpClient;
  72.  
  73. protected static StringBuilder userAgent;
  74.  
  75. protected Context context;
  76.  
  77. protected String url;
  78.  
  79. private HttpParams httpParameters;
  80.  
  81. private int timeoutConnection = 60000;
  82.  
  83. private int timeoutSocket = 60000;
  84.  
  85. private ArrayList<NameValuePair> params;
  86.  
  87. private Map<String, String> headers;
  88.  
  89. private HttpEntity entity;
  90.  
  91. private HttpMethod method;
  92.  
  93. private int responseCode;
  94.  
  95. private String response;
  96.  
  97. private HttpResponse httpResponse;
  98.  
  99. private HttpRequestBase request;
  100.  
  101. private String responseErrorMessage;
  102.  
  103. public BaseHttpClient(String url, Context context) {
  104.  
  105. this.url = url;
  106. this.context = context;
  107. this.params = new ArrayList<>();
  108. this.headers = new HashMap<>();
  109.  
  110. // default to GET
  111. this.method = HttpMethod.GET;
  112. request = new HttpGet(url);
  113.  
  114. httpParameters = new BasicHttpParams();
  115. httpParameters.setParameter(ConnManagerPNames.MAX_TOTAL_CONNECTIONS, 1);
  116. httpParameters.setParameter(
  117. ConnManagerPNames.MAX_CONNECTIONS_PER_ROUTE,
  118. new ConnPerRouteBean(1));
  119.  
  120. httpParameters.setParameter(HttpProtocolParams.USE_EXPECT_CONTINUE,
  121. false);
  122. HttpProtocolParams.setVersion(httpParameters, HttpVersion.HTTP_1_1);
  123. HttpProtocolParams.setContentCharset(httpParameters, "utf8");
  124. // Set the timeout in milliseconds until a connection is established.
  125. HttpConnectionParams.setConnectionTimeout(httpParameters,
  126. timeoutConnection);
  127.  
  128. // in milliseconds which is the timeout for waiting for data.
  129. HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
  130.  
  131. SchemeRegistry schemeRegistry = new SchemeRegistry();
  132.  
  133. // http scheme
  134. schemeRegistry.register(new Scheme("http", PlainSocketFactory
  135. .getSocketFactory(), 80));
  136. // https scheme
  137. try {
  138. schemeRegistry.register(new Scheme("https",
  139. new TrustedSocketFactory(url, false), 443));
  140. } catch (KeyManagementException e) {
  141. // TODO Auto-generated catch block
  142. e.printStackTrace();
  143. } catch (NoSuchAlgorithmException e) {
  144. // TODO Auto-generated catch block
  145. e.printStackTrace();
  146. }
  147. ThreadSafeClientConnManager manager = new ThreadSafeClientConnManager(
  148. httpParameters, schemeRegistry);
  149.  
  150. httpClient = new DefaultHttpClient(manager, httpParameters);
  151.  
  152. // support basic auth header
  153. try {
  154. URI uri = new URI(url);
  155. String userInfo = uri.getUserInfo();
  156. if (userInfo != null) {
  157. setHeader("Authorization", "Basic " + base64Encode(userInfo));
  158. }
  159. } catch (URISyntaxException e) {
  160. debug(e);
  161. }
  162.  
  163. // add user-agent header
  164. try {
  165. final String versionName = context.getPackageManager().getPackageInfo(
  166. context.getPackageName(), 0).versionName;
  167. // Add version name to user agent
  168. userAgent = new StringBuilder("SMSSync-Android/");
  169. userAgent.append("v");
  170. userAgent.append(versionName);
  171. setHeader("User-Agent", userAgent.toString());
  172. } catch (NameNotFoundException e) {
  173. debug(e);
  174. }
  175. }
  176.  
  177. public static String base64Encode(String str) {
  178. byte[] bytes = str.getBytes();
  179. return Base64.encodeToString(bytes, Base64.NO_WRAP);
  180. }
  181.  
  182. public static Throwable getRootCause(Throwable throwable) {
  183. if (throwable.getCause() != null) {
  184. return getRootCause(throwable.getCause());
  185. }
  186. return throwable;
  187. }
  188.  
  189. public static String convertStreamToString(InputStream is) {
  190.  
  191. BufferedReader reader = new BufferedReader(new InputStreamReader(is,
  192. Charset.forName("UTF-8")));
  193. StringBuilder sb = new StringBuilder();
  194.  
  195. int cp;
  196. try {
  197. while ((cp = reader.read()) != -1) {
  198. sb.append((char) cp);
  199. }
  200. } catch (IOException e) {
  201. debug(e);
  202. } finally {
  203. try {
  204. is.close();
  205. } catch (IOException e) {
  206. debug(e);
  207. }
  208. }
  209. return sb.toString();
  210. }
  211.  
  212. private static void debug(Exception e) {
  213. Logger.log(CLASS_TAG, "Exception: "
  214. + e.getClass().getName()
  215. + " " + getRootCause(e).getMessage());
  216. }
  217.  
  218. public String getResponse() {
  219. return response;
  220. }
  221.  
  222. public HttpResponse getResponseObject() {
  223. return httpResponse;
  224. }
  225.  
  226. public String getResponseErrorMessage() {
  227. return responseErrorMessage;
  228. }
  229.  
  230. public int responseCode() {
  231. return responseCode;
  232. }
  233.  
  234. public void addParam(String name, String value) {
  235. params.add(new BasicNameValuePair(name, value));
  236. }
  237.  
  238. public ArrayList getParams() {
  239. return params;
  240. }
  241.  
  242. public void setHeader(String name, String value) {
  243. headers.put(name, value);
  244. request.setHeader(name, value);
  245. }
  246.  
  247. public HttpRequestBase getRequest() throws Exception {
  248. prepareRequest();
  249. return request;
  250. }
  251.  
  252. public boolean isMethodSupported(HttpMethod method) {
  253. return (method.equals(HttpMethod.GET) || method.equals(HttpMethod.POST) || method
  254. .equals(HttpMethod.PUT));
  255. }
  256.  
  257. public void setMethod(HttpMethod method) throws Exception {
  258. if (!isMethodSupported(method)) {
  259. throw new Exception(
  260. "Invalid method '" + method + "'."
  261. + " POST, PUT and GET currently supported."
  262. );
  263. }
  264. this.method = method;
  265. }
  266.  
  267. public String getQueryString() throws Exception {
  268. //add query parameters
  269. String combinedParams = "";
  270. if (!params.isEmpty()) {
  271. combinedParams += "?";
  272. for (NameValuePair p : params) {
  273. String paramString = p.getName() + "=" + URLEncoder
  274. .encode(p.getValue(), DEFAULT_ENCODING);
  275. if (combinedParams.length() > 1) {
  276. combinedParams += "&" + paramString;
  277. } else {
  278. combinedParams += paramString;
  279. }
  280. }
  281. }
  282. return combinedParams;
  283. }
  284.  
  285. public HttpEntity getEntity() throws Exception {
  286. // check if entity was explicitly set otherwise return params as entity
  287. if (entity != null && entity.getContentLength() > 0) {
  288.  
  289. return entity;
  290. } else if (!params.isEmpty()) {
  291. // construct entity if not already set
  292. return new UrlEncodedFormEntity(params, DEFAULT_ENCODING);
  293. }
  294.  
  295. return null;
  296. }
  297.  
  298. public void setEntity(HttpEntity data) throws Exception {
  299. entity = data;
  300. }
  301.  
  302. public void setStringEntity(String data) throws Exception {
  303. entity = new StringEntity(data, DEFAULT_ENCODING);
  304. }
  305.  
  306. public void execute() throws Exception {
  307.  
  308. try {
  309. httpResponse = httpClient.execute(getRequest());
  310. responseCode = httpResponse.getStatusLine().getStatusCode();
  311. responseErrorMessage = httpResponse.getStatusLine().getReasonPhrase();
  312. final HttpEntity entity = httpResponse.getEntity();
  313.  
  314. if (entity != null) {
  315. InputStream instream = entity.getContent();
  316. response = convertStreamToString(instream);
  317. // Closing the input stream will trigger connection release
  318. instream.close();
  319. }
  320.  
  321. } catch (ClientProtocolException e) {
  322. httpClient.getConnectionManager().shutdown();
  323. throw e;
  324. } catch (Exception e) {
  325. e.printStackTrace();
  326. httpClient.getConnectionManager().shutdown();
  327. throw e;
  328. }
  329. }
  330.  
  331. private void prepareRequest() throws Exception {
  332. // setup parameters on request
  333. if (method.equals(HttpMethod.GET)) {
  334.  
  335. request = new HttpGet(url + getQueryString());
  336.  
  337. } else if (method.equals(HttpMethod.POST)) {
  338.  
  339. request = new HttpPost(url);
  340.  
  341. if (getEntity() != null) {
  342. ((HttpPost) request).setEntity(getEntity());
  343. }
  344.  
  345. } else if (method.equals(HttpMethod.PUT)) {
  346.  
  347. request = new HttpPut(url);
  348. if (getEntity() != null) {
  349. ((HttpPut) request).setEntity(getEntity());
  350. }
  351.  
  352. }
  353.  
  354. // set headers on request
  355. for (String key : headers.keySet()) {
  356. request.setHeader(key, headers.get(key));
  357. }
  358. }
  359.  
  360. protected void log(String message) {
  361. Logger.log(getClass().getName(), message);
  362. }
  363.  
  364. protected void log(String format, Object... args) {
  365. Logger.log(getClass().getName(), format, args);
  366. }
  367.  
  368. protected void log(String message, Exception ex) {
  369. Logger.log(getClass().getName(), message, ex);
  370. }
  371.  
  372. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement