Android Open Source - RestLib Https Client






From Project

Back to project page RestLib.

License

The source code is released under:

MIT License

If you think the Android project RestLib listed in this page is inappropriate, such as containing malicious code/tools or violating the copyright, please email info at java2s dot com, thanks.

Java Source Code

package github.crazymumu.restlib.core;
//  www  .  ja va2s  .  co m
import github.crazymumu.restlib.RestRequest;
import github.crazymumu.restlib.RestResponse;
import github.crazymumu.restlib.http.RequestMethod;
import github.crazymumu.restlib.http.StatusCode;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;

/**
 * HTTPS clients encapsulate a smorgasbord of objects required to execute HTTPS
 * requests while handling cookies, authentication, connection management, and
 * other features. Thread safety of HTTP clients depends on the implementation
 * and configuration of the specific client.
 * 
 * @author Crazy MuMu
 */
public class HttpsClient {
  public final static int DEFAULT_CONNECTION_TIMEOUT = 10000;
  public final static int DEFAULT_SOCKET_TIMEOUT = 10000;
  public final static String DEFAULT_CHARSET = "UTF-8";
  
  public static HttpClient getClient() {
    HttpClient client = new DefaultHttpClient();

    try {
      HttpParams params = client.getParams();
      HttpConnectionParams.setConnectionTimeout(params, HttpsClient.DEFAULT_CONNECTION_TIMEOUT);
      HttpConnectionParams.setSoTimeout(params, HttpsClient.DEFAULT_SOCKET_TIMEOUT);
      HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
      HttpProtocolParams.setContentCharset(params, DEFAULT_CHARSET);
      
      KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
      keyStore.load(null, null);
      SSLSocketFactory factory = new CustomSSLSocketFactory(keyStore);
      factory.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
      SchemeRegistry registry = new SchemeRegistry();
      registry.register(new Scheme("https", factory, 443));
      registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
      ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

      return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
      e.printStackTrace();
      return null;
    }
  }
  
  public RestResponse execute(RestRequest request) {
    HttpClient client = HttpsClient.getClient();
    HttpUriRequest uriRequest = null;
    HttpResponse response = null;
    String result = "";
    RestResponse restResponse = null;
    
    try {
      uriRequest = getUriRequest(request);
      response = client.execute(uriRequest);
      HttpEntity entity = response.getEntity();
      
      if (entity != null) {
        InputStream is = null;
        
        try {
          is = entity.getContent();
          result = convertStreamToString(is);
        } catch (IllegalStateException e) {
          e.printStackTrace();
        } catch (IOException e) {
          e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
          try {
            is.close();
          } catch (IOException e) {
            e.printStackTrace();
          } catch (Exception e) {
            e.printStackTrace();
          }
        }
      }
    } catch (ClientProtocolException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      if (response == null) {
        restResponse = new RestResponse(request.getResource(), request.getMethod(), StatusCode.ServiceUnavailable, result);
      } else {
        restResponse = new RestResponse(request.getResource(), request.getMethod(), response.getStatusLine().getStatusCode(), result);
      }
    }
    
    return restResponse;
  }
  
  private String convertStreamToString(InputStream is) {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line = null;
    
    try {
      while ((line = reader.readLine()) != null) {
        sb.append(line + "\n");
      }
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      try {
        is.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    
    return sb.toString();
  }
  
  private HttpUriRequest getUriRequest(RestRequest request) {
    HttpUriRequest uriRequest = null;
    
    if (RequestMethod.Get.equals(request.getMethod())) {
      uriRequest = new HttpGet(request.getResource() + getQueryString(request.getParams()));
    } else if (RequestMethod.Post.equals(request.getMethod())) {
      uriRequest = new HttpPost(request.getResource());
      ((HttpPost) uriRequest).setEntity(getHttpEntity(uriRequest, request.getParams()));
    } else if (RequestMethod.Delete.equals(request.getMethod())) {
      uriRequest = new HttpDelete(request.getResource());
    } else if (RequestMethod.Put.equals(request.getMethod())) {
      uriRequest = new HttpPut(request.getResource());
      ((HttpPut) uriRequest).setEntity(getHttpEntity(uriRequest, request.getParams()));
    }
    
    if (uriRequest != null) {
      uriRequest.setHeader("User-Agent", request.getUserAgent());
      
      for (Map.Entry<String, String> entry : request.getHeaders().entrySet()) {
        uriRequest.setHeader(entry.getKey(), entry.getValue());
      }
    }
    
    return uriRequest;
  }
  
  private HttpEntity getHttpEntity(HttpUriRequest request, Map<String, String> params) {
    HttpEntity entity = null;
    
    if (params.containsKey("")) {
      try {
        entity = new StringEntity(params.get(""));
      } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
      }
      
      request.setHeader("Accept", "application/json");
      request.setHeader("Content-type", "application/json");
    } else {
      entity = getUrlEncodedFormEntity(params);
      request.setHeader("Content-type", "application/x-www-form-urlencoded");
    }
    
    return entity;
  }
  
  private UrlEncodedFormEntity getUrlEncodedFormEntity(Map<String, String> params) {
    UrlEncodedFormEntity entity = null;
    List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    
    for (Map.Entry<String, String> entry : params.entrySet()) {
      nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
    }
    
    try {
      entity = new UrlEncodedFormEntity(nameValuePairs);
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    
    return entity;
  }
  
  private String getQueryString(Map<String, String> params) {
    StringBuilder sb = new StringBuilder();
    
    for (Map.Entry<String, String> entry : params.entrySet()) {
      sb.append(entry.getKey() + "=" + entry.getValue() + "&");
    }
    
    if (sb.length() > 0) {
      sb.insert(0, "?");
      sb.deleteCharAt(sb.length() - 1);
    }
    
    return sb.toString();
  }
}




Java Source Code List

github.crazymumu.restlib.RestRequest.java
github.crazymumu.restlib.RestResponse.java
github.crazymumu.restlib.RestResultReceiver.java
github.crazymumu.restlib.RestResult.java
github.crazymumu.restlib.RestService.java
github.crazymumu.restlib.core.CustomSSLSocketFactory.java
github.crazymumu.restlib.core.HttpsClient.java
github.crazymumu.restlib.core.SSLContextAlgorithm.java
github.crazymumu.restlib.http.RequestMethod.java
github.crazymumu.restlib.http.StatusCode.java
github.crazymumu.restlib.http.UserAgent.java
github.crazymumu.restlib.sample.MainActivity.java