Android Open Source - VideoExtand Http Util






From Project

Back to project page VideoExtand.

License

The source code is released under:

Apache License

If you think the Android project VideoExtand 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

/*
 * ??????HttpUtil.java/*  ww w.ja v a  2  s .  c o  m*/
 * ?????<????>
 * ?????<????>
 * ????xiaoying
 * ?????2013-7-30
 * ????xiaoying
 * ?????2013-7-30
 * ???v1.0
 */

package com.yuninfo.videoextand.utils;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.util.EntityUtils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.widget.Toast;

import com.google.gson.Gson;

/**
 * ???
 * 
 * @author xiaoying
 * 
 */
public class HttpUtil {
  
  public static final int OK = 200;
  
  public static final int SUCCES = 1;
  
  public static final int FAILED = 0;
  
  public static final int NET_ERROR = 2;
  
  public static final int FILE_NOT_FOUND = 3;
  
  public static final int IO_ERROR = 4;
  
  public static final int URI_ERROR = 5;
  
  public static final int JSON_ERROR = 6;

  private static String TAG = HttpUtil.class.getSimpleName();

  /**
   * ????URL????????URLConnection???
   * 
   * @param path
   * @return
   * @throws MalformedURLException
   * @throws IOException
   */
  public static InputStream getInputStreamByUrl(String url)
      throws MalformedURLException, IOException {
    LogUtil.w(TAG, "Request url +++++ " + url);
    URL httpUrl = new URL(url);
    HttpURLConnection conn = (HttpURLConnection) httpUrl.openConnection();
    conn.setConnectTimeout(10 * 1000);
    conn.setDoInput(true);
    conn.setDoOutput(true);
    conn.setRequestMethod("POST");
    conn.setRequestProperty("Content-Type", "*/*");
    conn.setRequestProperty("Connection", "Keep-Alive");
    conn.connect();
    return conn.getInputStream();
  }

  /**
   * ????URL????????Get??
   * 
   * @param url
   * @return
   * @throws ClientProtocolException
   * @throws IOException
   */
  public static InputStream getInputStreamByGet(String url)
      throws ClientProtocolException, IOException {
    LogUtil.w(TAG, "Request url +++++ " + url);
    DefaultHttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet(url);
    get.setHeader("Chartset", "UTF-8");
    HttpResponse resp = client.execute(get);
    return resp.getEntity().getContent();
  }

  public static String getStringFromUrl(String path)
      throws MalformedURLException, IOException {
    InputStream is = getInputStreamByUrl(path);
    StringBuilder sb = new StringBuilder();
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    String line = null;
    while ((line = br.readLine()) != null) {
      sb.append(line);
    }
    is.close();
    br.close();
    return sb.toString();
  }
  
  public static HttpResponse doPost(String url, String cookie, Object bean)
      throws ClientProtocolException, IOException, URISyntaxException {
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, 1000 * 30);
    HttpConnectionParams.setSoTimeout(httpParameters, 1000 * 300);
    HttpConnectionParams.setTcpNoDelay(httpParameters, true);
    HttpClient httpclient = new DefaultHttpClient(httpParameters);
    HttpPost request = new HttpPost(url);
    MultipartEntity multiEntity = new MultipartEntity();
    Map<String, Object> params = BeanRefUtil.getFieldValueMap(bean);
    LogUtil.i(TAG, params);
    Iterator<Entry<String, Object>> iterator = params.entrySet().iterator();
    while(iterator.hasNext()) {
      Entry<String, Object> entry = iterator.next();
      String key = entry.getKey();
      Object obj = entry.getValue();
      if (obj instanceof File) {
        File file = (File) params.get(key);
        if (!file.exists()) {
          throw new FileNotFoundException("File:" + file.getAbsolutePath() + "not found");
        }
        multiEntity.addPart(key, new FileBody(file, "*/*"));
      } else if(obj instanceof List) {
        multiEntity.addPart(key, new StringBody(obj == null ? "" : new Gson().toJson(obj), Charset.forName("utf-8")));
      } else {
        multiEntity.addPart(key, new StringBody(obj == null ? "" : obj.toString(), Charset.forName("utf-8")));
      }
    }
    request.setEntity(multiEntity);
    LogUtil.i(TAG, request.getRequestLine());
    if(!StringUtil.isEmpty(cookie)) {
      request.addHeader("Cookie", cookie);
    }
    request.addHeader("Connection", "keep-alive");
    request.addHeader("Chartset", "UTF-8");
    HttpResponse response = httpclient.execute(request);
    return response;
  }
  
  public static String getCookie(HttpResponse httpResponse) {
    Header header = httpResponse.getFirstHeader("Set-Cookie");
    if(header == null) {
      return  null;
    }
    return header.getValue();
  }
  
  public static int getStatusCode(HttpResponse resp) {
    if(resp == null) {
      return -1;
    }
    return resp.getStatusLine().getStatusCode();
  }
  
  public static String getReasonPhrase(HttpResponse resp) {
    if(resp == null) {
      return "??????";
    }
    return resp.getStatusLine().getReasonPhrase();
  }

  /**
   * HttpGet??
   * 
   * @param url
   * @return
   * @throws URISyntaxException
   * @throws ClientProtocolException
   * @throws IOException
   */
  public static HttpResponse doGet(String url) throws URISyntaxException,
      ClientProtocolException, IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpGet get = new HttpGet(new URI(url));
    get.setHeader("Chartset", "UTF-8");
    return client.execute(get);
  }

  /**
   * ??????????(HttpGet??)
   * 
   * @param url
   * @param folder
   * @return
   * @throws URISyntaxException
   * @throws ClientProtocolException
   * @throws IOException
   */
  public static String downloadByGet(String url, String folder)
      throws URISyntaxException, ClientProtocolException, IOException,
      FileNotFoundException {
    InputStream is = getInputStreamByGet(url);
    File file = null;
    if (folder.endsWith("/")) {
      file = new File(folder + StringUtil.getFileName(url));
    } else {
      file = new File(folder + "/" + StringUtil.getFileName(url));
    }
    LogUtil.i(TAG, "Download url:" + url);
    LogUtil.i(TAG, "Download to:" + file.getAbsolutePath());
    DataOutputStream dos = new DataOutputStream(new FileOutputStream(file));
    byte[] buf = new byte[2048];
    int length = 0;
    while ((length = is.read(buf)) > 0) {
      dos.write(buf, 0, length);
    }
    is.close();
    dos.close();
    return file.getAbsolutePath();
  }

  /**
   * ????????????URLConnection????
   * 
   * @param url
   * @param folder
   * @return
   * @throws URISyntaxException
   * @throws ClientProtocolException
   * @throws IOException
   */
  public static String downloadByUrl(String url, String folder)
      throws URISyntaxException, ClientProtocolException, IOException {
    InputStream is = getInputStreamByUrl(url);
    File file = null;
    if (folder.endsWith("/")) {
      file = new File(folder + StringUtil.getFileName(url));
    } else {
      file = new File(folder + "/" + StringUtil.getFileName(url));
    }
    LogUtil.i(TAG, "Download url:" + url);
    LogUtil.i(TAG, "Download to:" + file.getAbsolutePath());
    DataOutputStream dos = new DataOutputStream(new FileOutputStream(file));
    byte[] buf = new byte[2048];
    int length = 0;
    while ((length = is.read(buf)) > 0) {
      dos.write(buf, 0, length);
    }
    is.close();
    dos.close();
    return file.getAbsolutePath();
  }

  /**
   * ??????????
   * 
   * @param url
   * @param data
   * @return
   */
  public static String doHttpRequest(String url, Map<String, Object> data) {
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, 1000 * 30);
    HttpConnectionParams.setSoTimeout(httpParameters, 1000 * 30);
    HttpConnectionParams.setTcpNoDelay(httpParameters, true);
    HttpClient httpclient = new DefaultHttpClient(httpParameters);
    HttpPost request = new HttpPost(url);
    MultipartEntity multiEntiry = new MultipartEntity();
    Set<String> keys = data.keySet();
    try {
      for (String key : keys) {
        Object obj = data.get(key);
        if (obj instanceof File) {
          File file = (File) data.get(key);
          if (!file.exists()) {
            return null;
          }
          multiEntiry.addPart(key, new FileBody(file, "*/*"));
        } else {
          multiEntiry.addPart(key, new StringBody(obj.toString()));
        }
      }
      request.setEntity(multiEntiry);
      HttpResponse response = httpclient.execute(request);
      return EntityUtils.toString(response.getEntity());
    } catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
  
  public static boolean isNetworkAvairable(Context context) {
    final ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
      final NetworkInfo networkInfo = cm.getActiveNetworkInfo();
      if (networkInfo == null || !networkInfo.isConnectedOrConnecting()) {
          Toast.makeText(context, "????????????", Toast.LENGTH_LONG).show();
          LogUtil.e(TAG, "checkConnection - no connection found");
          return false;
      }
      return true;
  }
}




Java Source Code List

com.example.androidtest.MainActivity.java
com.yuninfo.videoextand.BaseActivity.java
com.yuninfo.videoextand.Config.java
com.yuninfo.videoextand.ReadCardActivity.java
com.yuninfo.videoextand.SendCardActivity.java
com.yuninfo.videoextand.bean.CommonReq.java
com.yuninfo.videoextand.bean.ReadVideoResp.java
com.yuninfo.videoextand.bean.SendVideoResp.java
com.yuninfo.videoextand.bean.UploadReq.java
com.yuninfo.videoextand.bean.UploadResp.java
com.yuninfo.videoextand.player.VideoPlayerActivity.java
com.yuninfo.videoextand.recorder.RecorderActivity.java
com.yuninfo.videoextand.uploader.ProgressListener.java
com.yuninfo.videoextand.uploader.ProgressMultipartEntity.java
com.yuninfo.videoextand.uploader.ProgressOutputStream.java
com.yuninfo.videoextand.uploader.UploadHandler.java
com.yuninfo.videoextand.uploader.UploadThread.java
com.yuninfo.videoextand.utils.BeanRefUtil.java
com.yuninfo.videoextand.utils.DateUtil.java
com.yuninfo.videoextand.utils.FileUtil.java
com.yuninfo.videoextand.utils.HttpUtil.java
com.yuninfo.videoextand.utils.LogUtil.java
com.yuninfo.videoextand.utils.StringUtil.java
com.yuninfo.videoextand.widget.CustomPopupWindow.java
com.yuninfo.videoextand.widget.TitleBar.java
com.yuninfo.videoextand.widget.dialog.MenuDialog.java