LocalHttpClient.java :  » Web » pockerface » com » softright » net » Android Open Source

Android Open Source » Web » pockerface 
pockerface » com » softright » net » LocalHttpClient.java
package com.softright.net;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;

import android.content.Context;
import android.graphics.Bitmap;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Log;

import com.lemon.activity.WebActivity;
import com.lemon.tools.Constants;
import com.lemon.tools.Utils;

/**
 * @author lemon
 * 
 */
public class LocalHttpClient {

  final static int TIME_OUT = 20000;

  public static boolean isNetworkAvailable() {
    Context context = WebActivity.getApp();
    ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    if (connectivity == null) {
      Log.d("UI", "getSystemService rend null");
    } else {
      NetworkInfo[] info = connectivity.getAllNetworkInfo();
      if (info != null) {
        for (int i = 0; i < info.length; i++) {
          if (info[i].getState() == NetworkInfo.State.CONNECTED) {
            Log.d("UI", "active network status state:" + info[i].getState());
            Log.d("UI", "active network status subTypeName:" + info[i].getSubtypeName());
            Log.d("UI", "active network status typeName:" + info[i].getTypeName());
            Constants.SPF.edit().putString("network_type", info[i].getTypeName()).commit();
            return true;
          }
        }
      }
      // httpGet("http://www.baidu.com",null);
      // Log.d("UI", "b:" + b.toString());
      // if (b.toString().length() == 0) {
      // Constants.ISNETOK = false;
      // Log.d("UI", "isNetworkAvailable:" + Constants.ISNETOK);
      // }
      // return Constants.ISNETOK;
    }
    return false;
  }

  public static String httpPost(String urlHead, String postKey, String postValue) {
    StringBuffer url = new StringBuffer();
    StringBuilder builder = new StringBuilder();
    HttpResponse response = null;
    url.append(urlHead);
    DefaultHttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(url.toString());
    Log.d("lemon", "httpPost:" + url.toString());
    post.addHeader(new BasicHeader("Content-Type", "application/x-www-form-urlencoded"));
    post.getParams().setIntParameter("http.socket.timeout", TIME_OUT);
    List<NameValuePair> nvpList = null;
    if ((postKey != null) && (postValue != null)) {
      NameValuePair nvp = new BasicNameValuePair(postKey, postValue);
      nvpList = new ArrayList<NameValuePair>();
      nvpList.add(nvp);
    }
    try {
      if (!nvpList.isEmpty())
        post.setEntity(new UrlEncodedFormEntity(nvpList, "utf-8"));
    } catch (UnsupportedEncodingException e1) {
      e1.printStackTrace();
    }
    try {
      response = client.execute(post);
      if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        post.abort();
        Constants.ISNETOK = false;
      } else {
        Constants.ISNETOK = true;
      }
    } catch (Exception e) {

    }
    try {
      BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
      for (String s = reader.readLine(); s != null; s = reader.readLine()) {
        builder.append(s);
      }
    } catch (Exception e) {
      Log.d("lemon", "httpPost response error!");
      return null;
    } finally {
      client.getConnectionManager().shutdown();
    }
    return builder.toString();
  }

  public static String httpGet(String urlHeader, String content) {
    StringBuffer url = new StringBuffer();
    HttpClient client = new DefaultHttpClient();
    HttpResponse response = null;
    StringBuilder b = new StringBuilder();
    url.append(urlHeader);
    if (content != null) {
      url.append(content);
    }
    Log.d("lemon", "httpGet:" + url.toString());
    HttpGet get = new HttpGet(url.toString());
    get.getParams().setIntParameter("http.socket.timeout", TIME_OUT);
    try {
      response = client.execute(get);
      if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        get.abort();
        Constants.ISNETOK = false;
      } else {
        Constants.ISNETOK = true;
      }
    } catch (IOException e) {
    }
    try {
      BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
      for (String s = reader.readLine(); s != null; s = reader.readLine()) {
        b.append(s);
      }
    } catch (Exception e) {
      Log.d("lemon", "httpGet response error!");
      return null;
    } finally {
      client.getConnectionManager().shutdown();
    }
    Log.d("lemon", b.toString());
    return b.toString();
  }

  /**
   * POST
   * 
   * @param path
   *            
   * @param params
   *            
   * @return
   * @throws Exception
   */
  public static String httpPostFile(String path) throws Exception {
    StringBuilder builder = new StringBuilder();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    Constants.BM.compress(Bitmap.CompressFormat.JPEG, 100, out);
    byte[] data = out.toByteArray();
    URL url = new URL(path);
    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
    conn.setRequestMethod("POST");
    conn.setConnectTimeout(5 * 1000);
    conn.setDoOutput(true);
    conn.setRequestProperty("Content-Type", "multipart/form-data");
    conn.setRequestProperty("Content-Length", URLDecoder.decode(String.valueOf(data.length), "UTF-8"));
    OutputStream outStream = conn.getOutputStream();
    outStream.write(data);
    outStream.flush();
    outStream.close();
    try {
      BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
      for (String s = reader.readLine(); s != null; s = reader.readLine()) {
        builder.append(s);
      }
    } catch (Exception e) {
      Log.d("lemon", "httpPostFile response error!");
      return null;
    }
    return builder.toString();
  }

  public static String httpPostMultiMedia(String urlHead) {
    FileUpload fileUpload = new FileUpload();
    MutilPartEntity entity = new MutilPartEntity();
    StringBuffer url = new StringBuffer();
    String rtl = new String();
    url.append(urlHead);
    Log.d("lemon", "httpPostFiles:" + url.toString());

    // StringBody stringData = new StringBody("syncContacts", "String");
    // entity.addBody(stringData);
    BytesBody imageData = new BytesBody("image", Utils.Bitmap2Bytes(Constants.BM));
    entity.addBody(imageData);
    // FileBody soundData = new FileBody("context_sound", new
    // File(Constants.SOUND_PATH));
    // entity.addBody(soundData);
    // StringBody stringData1 = new StringBody("content",
    // Constants.WANT_TO_SEND.toString());
    // entity.addBody(stringData1);

    try {
      rtl = fileUpload.doUpload(url.toString(), entity);
      Log.d("lemon", "rlt:" + rtl);
    } catch (FileUploadException e) {
      Log.d("lemon", "FileUploadException error!");
      e.printStackTrace();
    } catch (Exception e) {
      Log.d("lemon", "Exception error!");
      e.printStackTrace();
    }
    return rtl;
  }

}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.