New Http Client Manager : Http Connection « Network « Android






New Http Client Manager

    

//package com.filmatchs.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
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.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;

import android.util.Log;

public class NewHttpClientManager {

  public static String LOG_TAG = "NewHttpClientManager";

  public static int METHOD_GET = 1;
  public static int METHOD_POST = 2;
  public static int METHOD_PUT = 3;
  public static int METHOD_DELETE = 4;

  private String result = "";

  /**
   * Do an HttpClient connection and store the result, the result could be
   * returned with getResult()
   * 
   * @param url
   * @param method
   * @param headers
   * @param entity
   * @param credential
   */
  public NewHttpClientManager(String url, int method,
      ArrayList<Header> headers, HttpEntity entity,
      UsernamePasswordCredentials credential)
      throws ClientProtocolException, IOException {
    try {
      result = connectResponse(url, method, headers, entity, credential, null);
    } catch (ClientProtocolException ex) {
      Log.e(LOG_TAG, "ClientProtocol Exception");
      ex.printStackTrace();
    } catch (IOException ex) {
      Log.e(LOG_TAG, "IO Exception");
      ex.printStackTrace();
    }
  }
  
  public NewHttpClientManager(String url, int method,
      ArrayList<Header> headers, HttpEntity entity,
      UsernamePasswordCredentials credential, HttpHost host)
      throws ClientProtocolException, IOException {
    try {
      result = connectResponse(url, method, headers, entity, credential, host);
    } catch (ClientProtocolException ex) {
      Log.e(LOG_TAG, "ClientProtocol Exception");
      ex.printStackTrace();
    } catch (IOException ex) {
      Log.e(LOG_TAG, "IO Exception");
      ex.printStackTrace();
    }
  }

  /**
   * Do an HttpClient Connection, then returns the result
   * 
   * 
   * @param url
   * @param method
   * @param headers
   * @param entity
   * @param credential
   * @return
   * @throws ClientProtocolException
   * @throws IOException
   */
  public static String connectResponse(String url, int method,
      List<Header> headers, HttpEntity entity,
      UsernamePasswordCredentials credential, HttpHost host)
      throws ClientProtocolException, IOException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpResponse response;

    String retval = null;

    HttpEntityEnclosingRequest heer = null;

    // setting scheme for http/https
    final SSLSocketFactory sslSocketFactory = SSLSocketFactory
        .getSocketFactory();
    sslSocketFactory
        .setHostnameVerifier(SSLSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
    httpClient.getConnectionManager().getSchemeRegistry().register(
        new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
    httpClient.getConnectionManager().getSchemeRegistry().register(
        new Scheme("https", sslSocketFactory, 443));

    if (method == METHOD_POST) {
      // ------------------ POST

      Log.d(LOG_TAG, "POST to " + url);

      heer = new HttpPost(url);

      // Setting Entity if provided
      if (entity != null) {
        Log.d(LOG_TAG, "ENTITY PROVIDED");
        heer.setEntity(entity);
      }

      // Setting Headers if provided
      if (headers != null) {
        Log.d(LOG_TAG, "HEADERS PROVIDED");
        for (Header header : headers) {
          heer.setHeader(header);
        }
      }

      // Setting Credentials if provided
      if (credential != null) {
        Log.d(LOG_TAG, "CREDENTIAL PROVIDED : "
            + credential.getUserName() + ":"
            + credential.getPassword());
        httpClient.getCredentialsProvider().setCredentials(
            new AuthScope(AuthScope.ANY), credential);
      }

      // execute the request
      if (host != null) {
        response = httpClient.execute(host, (HttpPost) heer);
      } else {
        response = httpClient.execute((HttpPost) heer);
      }
    } else if (method == METHOD_PUT) {
      // ------------------ PUT
      response = httpClient.execute(new HttpPut(url));
    } else if (method == METHOD_DELETE) {
      // ------------------ DELETE
      response = httpClient.execute(new HttpDelete(url));
    } else {
      // ------------------ GET (DEFAULT: IF NOT POST, PUT, DELETE)
      response = httpClient.execute(new HttpGet(url));
    }

    Log.d(LOG_TAG, "StatusLine " + response.getStatusLine());

    // Setting the response entity
    entity = response.getEntity();

    // if entity is not null, then print it to the return value
    if (entity != null) {
      InputStream instream = entity.getContent();
      String result = convertStreamToString(instream);
      retval = result;
      instream.close();
    }

    // return it!
    return retval;
  }
  public static 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();
  }
  /**
   * Get response of the HttpClient Connection
   * 
   * @return
   */
  public String getResult() {
    return result;
  }
}

   
    
    
    
  








Related examples in the same category

1.Http Connection
2.Using HttpGet to get the web response
3.Create Http connection
4.Http connection with
5.HttpGet and DefaultHttpClient
6.Http Post
7.Simple HTTP Request
8.Http Request Class
9.Http Get and Http Post
10.Get Text from HttpResponse
11.Http Request
12.Http Downloader
13.Is Http Url Available
14.Http Retriever
15.Receive Response from HttpURLConnection
16.Print http headers. Useful for debugging.
17.Return the base URL from the given URL. Example: http://foo.org/abc.html -> http://foo.org/
18.Send message with HttpPost
19.Get Http Stream
20.Generic Object Http Loader
21.Http Get and DefaultHttpClient
22.Gets http output from URL
23.Util for Http Get
24.do Http Get Request and return the status code
25.Http Get
26.implements HttpClient
27.Get File From HTTP
28.Make all redirects to go to http in stead of https
29.Http Client Manager
30.Multipart Post
31.Get Server Data
32.Yahoo News Crawler
33.Send Packet
34.Read a web page
35.parse Request Header
36.Data Send Utils
37.This class is in charge of synchronizing the events (with due dates) with Google Calendar
38.Update Favicon
39.Converts key-value pair to appropriate signature for Facebook.