HTTPClient


SUBMITTED BY: Guest

DATE: Feb. 4, 2014, 5:20 p.m.

FORMAT: Java

SIZE: 8.3 kB

HITS: 1110

  1. package eftr2.dataservice2;
  2. import android.util.Log;
  3. import com.google.gson.Gson;
  4. import com.loopj.android.http.AsyncHttpClient;
  5. import com.loopj.android.http.AsyncHttpResponseHandler;
  6. import com.loopj.android.http.RequestParams;
  7. import org.apache.http.Header;
  8. import org.apache.http.conn.ssl.SSLSocketFactory;
  9. import org.apache.http.entity.StringEntity;
  10. import javax.net.ssl.SSLContext;
  11. import javax.net.ssl.TrustManager;
  12. import javax.net.ssl.X509TrustManager;
  13. import java.io.IOException;
  14. import java.io.UnsupportedEncodingException;
  15. import java.net.Socket;
  16. import java.net.UnknownHostException;
  17. import java.security.*;
  18. import java.security.cert.CertificateException;
  19. import java.security.cert.X509Certificate;
  20. import java.util.HashMap;
  21. import java.util.Map;
  22. public abstract class BaseHttpClient {
  23. private static final String TAG = "eftr2.dataservice2.BaseHttpClient";
  24. final static String JsonMIMEType = "application/json";
  25. final static String USER_AGENT = "EFTRM";
  26. private final static String ENCODING = "UTF-8";
  27. private final IUserIdenityService identityService;
  28. private final AsyncHttpClient client;
  29. protected final Gson gson = new Gson();
  30. private final String baseUri;
  31. public BaseHttpClient(String baseUri, IUserIdenityService identityService){
  32. this.baseUri = baseUri;
  33. this.identityService = identityService;
  34. String login = this.identityService.getLogin();
  35. String password = this.identityService.getPassword();
  36. this.client = AsyncHttpClientFactory.getAsyncHttpClient(login, password);
  37. }
  38. /**
  39. * @param path - ресурс на бекенде
  40. * @param params - параметры GET запроса
  41. * @param onResponce - callback для функции
  42. * @throws UnsupportedEncodingException
  43. */
  44. protected void GetAsync(String path, Map<String, String> params, final ResponseHandler<BaseResponse> onResponce) {
  45. // валидация входных параметров
  46. if (path == null || path.length() == 0)
  47. throw new InvalidParameterException("Invalid pathAndQuery parameter");
  48. if (params == null) params = new HashMap<String, String>();
  49. // отправляем запрос
  50. client.get(
  51. null, // android specific
  52. baseUri + path, // endpoint
  53. new RequestParams(params),
  54. getResponseHandler(onResponce));
  55. }
  56. /**
  57. * @param path - ресурс на бекенде
  58. * @param model - модель объекта
  59. * @param onResponse - callback для функции
  60. * @throws UnsupportedEncodingException
  61. */
  62. protected void PostAsync(String path, Object model, final ResponseHandler<BaseResponse> onResponse)
  63. {
  64. // валидация входных параметров
  65. if (path == null || path.length() == 0)
  66. throw new InvalidParameterException("Invalid pathAndQuery parameter");
  67. if(model==null) model = new Object();
  68. try
  69. {
  70. Log.d(TAG, "url = " + baseUri + path);
  71. client.post(
  72. null,
  73. baseUri + path, // endpoint
  74. new StringEntity(gson.toJson(model), ENCODING), // Body
  75. JsonMIMEType,
  76. getResponseHandler(onResponse));
  77. }
  78. catch(final Exception e){
  79. if(onResponse!=null){
  80. onResponse.OnDone(new BaseResponse(true, "599", e.getMessage(), null));
  81. }
  82. }
  83. }
  84. private AsyncHttpResponseHandler getResponseHandler(final ResponseHandler<BaseResponse> onResponce) {
  85. return new AsyncHttpResponseHandler() {
  86. @Override
  87. public void onSuccess(int statusCode, Header[] headers, byte[] responseBody) {
  88. Log.i(TAG, "");
  89. final boolean isFailed = statusCode > 300;
  90. onResponce.OnDone(
  91. new BaseResponse(
  92. isFailed,
  93. isFailed ? String.valueOf(statusCode) : null,
  94. null,
  95. responseBody
  96. )
  97. );
  98. }
  99. @Override
  100. public void onFailure(int statusCode, Header[] headers, byte[] responseBody, Throwable error) {
  101. Log.e(TAG, "");
  102. final boolean isFailed = statusCode > 300;
  103. onResponce.OnDone(
  104. new BaseResponse(
  105. isFailed,
  106. String.valueOf(statusCode),
  107. isFailed ? error.getMessage() : null,
  108. responseBody
  109. )
  110. );
  111. }
  112. };
  113. }
  114. }
  115. class AsyncHttpClientFactory
  116. {
  117. public static AsyncHttpClient getAsyncHttpClient(String login, String password){
  118. AsyncHttpClient client = new AsyncHttpClient();
  119. KeyStore trustStore = null;
  120. try {
  121. trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
  122. trustStore.load(null, null);
  123. final MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
  124. sf.setHostnameVerifier(MySSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
  125. client.setSSLSocketFactory(sf);
  126. } catch (Exception e) {
  127. throw new RuntimeException("Can't initiate client");
  128. }
  129. client.addHeader("Accept", BaseHttpClient.JsonMIMEType);
  130. client.setBasicAuth(login, password);
  131. //этот метод НЕ работает с упреждающей посылкой basic auth хедера, он сначала пытается всё сделать без посыла авторизации, ожидая что его пошлют на авторизационный урл, и после этого он пошлёт авторизацию...
  132. //подробнее http://stackoverflow.com/questions/15110497/asynchttpclient-authentication-failed
  133. //так что тупо запихаем хедер руками
  134. //client.addHeader("Authorization", "Basic " + Base64.encodeToString((login+":"+password).getBytes(), Base64.NO_WRAP));
  135. //client.setEnableRedirects(true);
  136. client.setUserAgent(BaseHttpClient.USER_AGENT);
  137. return client;
  138. }
  139. }
  140. class MySSLSocketFactory extends SSLSocketFactory {
  141. SSLContext sslContext = SSLContext.getInstance("TLS");
  142. public MySSLSocketFactory(KeyStore truststore) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException, UnrecoverableKeyException {
  143. super(truststore);
  144. TrustManager tm = new X509TrustManager() {
  145. public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  146. }
  147. public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
  148. }
  149. public X509Certificate[] getAcceptedIssuers() {
  150. return null;
  151. }
  152. };
  153. sslContext.init(null, new TrustManager[] { tm }, null);
  154. }
  155. @Override
  156. public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
  157. return sslContext.getSocketFactory().createSocket(socket, host, port, autoClose);
  158. }
  159. @Override
  160. public Socket createSocket() throws IOException {
  161. return sslContext.getSocketFactory().createSocket();
  162. }
  163. }

comments powered by Disqus