Android Open Source - doubanbook4android Net Utils






From Project

Back to project page doubanbook4android.

License

The source code is released under:

Eclipse Public License - v 1.0 THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECI...

If you think the Android project doubanbook4android 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 com.study.doubanbook_for_android.api;
/*  w ww  .j  a  v a  2  s  .  c o m*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
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.HttpGet;
import org.apache.http.client.methods.HttpPost;
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.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import com.study.doubanbook_for_android.auth.AccessToken;
import com.study.doubanbook_for_android.auth.KeepToken;

import android.content.Context;
import android.net.ParseException;
import android.util.Log;

public class NetUtils {
  public static final int GET = 0;
  public static final int POST = 1;

  /**
   * ???????????,???????????????????????,???NET??TAG
   * 
   * @param urls
   *            suburl basic is known to us
   * @param method
   *            get or post
   * @param keys
   *            ?????????????
   * @param values
   *            ???????????????
   * @return
   * @throws UnsupportedEncodingException
   */
  public static String getHttpEntity(String urls, int method,
      List<String> keys, List<String> values, Context context) {

    HttpResponse httpResponse = null;
    StringBuffer result = new StringBuffer();
    switch (method) {
    case GET:
      HttpGet httpGet = new HttpGet(getUrlStr(urls, values, keys));
      // add access_token if need,just send context to this is ok

      if (context != null) {
        AccessToken accessToken = KeepToken.readAccessToken(context);
        httpGet.addHeader("Authorization",
            "Bearer " + accessToken.getToken());
        httpGet.addHeader("access_token", accessToken.getToken());
      }
      try {
        httpResponse = getNewHttpClient().execute(httpGet);
      } catch (ClientProtocolException e) {
        Log.d("NET", e.getMessage());
        e.printStackTrace();
      } catch (IOException e) {
        Log.d("NET", e.getMessage());
        e.printStackTrace();
      }
      int statusCode = httpResponse.getStatusLine().getStatusCode();
      if (statusCode == HttpStatus.SC_OK) {
        try {
          result = new StringBuffer(EntityUtils.toString(httpResponse
              .getEntity()));
          // log out the result
          Log.d("NET", result.toString());
        } catch (ParseException e) {
          // log out the exception
          Log.d("NET", e.getMessage());
          e.printStackTrace();
        } catch (IOException e) {
          Log.d("NET", e.getMessage());
          e.printStackTrace();
        }
      } else {
        // get the wrong msg will return upstairs will charge
        // log out the status code and describe
        try {
          // log out the result,in business will be received by
          // wrongMsg model
          result = new StringBuffer(EntityUtils.toString(httpResponse
              .getEntity()));
        } catch (org.apache.http.ParseException e) {
          Log.d("NET", e.getMessage());
          e.printStackTrace();
        } catch (IOException e) {
          Log.d("NET", e.getMessage());
          e.printStackTrace();
        }
        Log.d("NET", "status code:  "
            + httpResponse.getStatusLine().getStatusCode());
        Log.d("NET", "status describe:  "
            + httpResponse.getStatusLine().getReasonPhrase());
      }
      break;
    case POST:
      HttpPost httpPost = new HttpPost(urls);
      try {
        // ??httpPost??????
        Log.d("NET", "POST " + urls);
        // add access_token if need,just send context to this is ok
        if (context != null) {
          AccessToken accessToken1 = KeepToken
              .readAccessToken(context);
          httpPost.addHeader("Authorization", "Bearer "
              + accessToken1.getToken());
          httpPost.addHeader("access_token", accessToken1.getToken());
        }
        httpPost.setEntity(new UrlEncodedFormEntity(getNameValuePair(
            keys, values), HTTP.UTF_8));
        // here remember user New HttpClient with SSL protocol
        httpResponse = getNewHttpClient().execute(httpPost);
        if (httpResponse.getStatusLine().getStatusCode() == 200) {
          result = new StringBuffer(EntityUtils.toString(httpResponse
              .getEntity()));
        } else {
          // get the wrong msg will return upstairs will charge
          // log out the status code and describe
          try {
            // log out the result,in business will be received by
            // wrongMsg model
            result = new StringBuffer(
                EntityUtils.toString(httpResponse.getEntity()));
            Log.d("NET", result.toString());
          } catch (org.apache.http.ParseException e) {
            Log.d("NET", e.getMessage());
            e.printStackTrace();
          } catch (IOException e) {
            Log.d("NET", e.getMessage());
            e.printStackTrace();
          }
          Log.d("NET", "status code:  "
              + httpResponse.getStatusLine().getStatusCode());
          Log.d("NET", "status describe:  "
              + httpResponse.getStatusLine().getReasonPhrase());
        }
      } catch (ClientProtocolException e) {
        Log.d("NET", e.getMessage());
        e.printStackTrace();
      } catch (IOException e) {
        Log.d("NET", e.getMessage());
        e.printStackTrace();
      }
      break;

    /**
     * ???????SSL????????????,???????????? updatatime: 2013-12-13
     */
    case 3 /* old get */:
      try {
        URL url = new URL(getUrlStr(urls, values, keys));
        URLConnection connection = url.openConnection();
        String line;
        BufferedReader in = new BufferedReader(new InputStreamReader(
            connection.getInputStream(), "UTF-8"));
        while ((line = in.readLine()) != null) {
          result.append(line);
        }
      } catch (Exception e) {
        e.printStackTrace();
      }
      break;
    default:
      break;
    }
    Log.d("NET", result.toString());
    return result.toString();
  }

  // ------other basic method
  /**
   * attach params to url
   * 
   * @param urls
   * @param values
   * @param keys
   * @return
   */
  private static String getUrlStr(String urls, List<String> values,
      List<String> keys) {
    StringBuffer urlBuffer = new StringBuffer(urls);
    if (keys.size() == 0 || keys == null)
      return urlBuffer.toString();
    if (keys.size() >= 1) {
      // params start
      urlBuffer.append("?");
      // ensure the right Url encode
      urlBuffer.append(keys.get(0)).append("=").append(values.get(0));
      Log.d("NET",
          "parms" + (1) + ":" + keys.get(0) + "=" + values.get(0));
      for (int i = 1; i < keys.size(); i++) {
        // another key value pair and show the params
        urlBuffer.append("&");
        urlBuffer.append(keys.get(i)).append("=").append(values.get(i));
        Log.d("NET", "parms" + (i + 1) + ":" + keys.get(i) + "="
            + values.get(i));
      }
    }
    Log.d("NET", "url:" + urlBuffer.toString());
    return urlBuffer.toString();

  }

  /**
   * for https or http connection defined a httpclient
   * HTTPS:?????????????HTTP???????SSL/TSL????????????443
   * 1.peer?????????request?https?????????????????????????????????????ca???????????????
   * 2.???????????????????????? 3.??????????????????????? 4.request
   * https???????????????????https????? 5.https??????????????????????
   * 6.????????????????????????????
   * 
   * @return httpclient
   */
  public static HttpClient getNewHttpClient() {
    try {
      KeyStore trustStore = KeyStore.getInstance(KeyStore
          .getDefaultType());
      trustStore.load(null, null);

      SSLSocketFactory sf = new SSLSocketFactoryEx(trustStore);
      sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

      HttpParams params = new BasicHttpParams();
      HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
      HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

      SchemeRegistry registry = new SchemeRegistry();
      registry.register(new Scheme("http", PlainSocketFactory
          .getSocketFactory(), 80));
      registry.register(new Scheme("https", sf, 443));

      ClientConnectionManager ccm = new ThreadSafeClientConnManager(
          params, registry);

      return new DefaultHttpClient(ccm, params);
    } catch (Exception e) {
      return new DefaultHttpClient();
    }
  }

  private static List<NameValuePair> getNameValuePair(List<String> keys,
      List<String> values) {
    // ??HTTP POST?????????NameValuePair??
    List<NameValuePair> params = new ArrayList<NameValuePair>();
    if (keys != null)
      for (int i = 0; i < keys.size(); i++) {
        params.add(new BasicNameValuePair(keys.get(i), values.get(i)));
        Log.d("NET", "parms" + (i + 1) + ":" + keys.get(i) + "="
            + values.get(i));
      }
    return params;
  }
}




Java Source Code List

.UserListAdapter.java
com.study.doubanbook_for_android.activity.BaseActivity.java
com.study.doubanbook_for_android.activity.BaseP2RActivity.java
com.study.doubanbook_for_android.activity.BookDetailActivity.java
com.study.doubanbook_for_android.activity.BookListsActivity.java
com.study.doubanbook_for_android.activity.BookNoteListActivity.java
com.study.doubanbook_for_android.activity.CollectDetailActivity.java
com.study.doubanbook_for_android.activity.NoteAndUserDetailActivity.java
com.study.doubanbook_for_android.activity.SerchInputActivity.java
com.study.doubanbook_for_android.activity.TextActivity1.java
com.study.doubanbook_for_android.activity.UserDetailActivity.java
com.study.doubanbook_for_android.activity.UserListActivity.java
com.study.doubanbook_for_android.activity.UserNoteActivity.java
com.study.doubanbook_for_android.adapter.BookAdapter.java
com.study.doubanbook_for_android.adapter.CommentAdapter.java
com.study.doubanbook_for_android.adapter.UserNoteAdapter.java
com.study.doubanbook_for_android.api.NetUtils.java
com.study.doubanbook_for_android.api.SSLSocketFactoryEx.java
com.study.doubanbook_for_android.api.WrongMsg.java
com.study.doubanbook_for_android.auth.AccessToken.java
com.study.doubanbook_for_android.auth.DoubanDialogError.java
com.study.doubanbook_for_android.auth.DoubanDialog.java
com.study.doubanbook_for_android.auth.DoubanException.java
com.study.doubanbook_for_android.auth.DoubanOAuthListener.java
com.study.doubanbook_for_android.auth.DoubanParameters.java
com.study.doubanbook_for_android.auth.DoubanRequest.java
com.study.doubanbook_for_android.auth.Douban.java
com.study.doubanbook_for_android.auth.KeepToken.java
com.study.doubanbook_for_android.auth.SimpleDoubanOAuthListener.java
com.study.doubanbook_for_android.auth.Token.java
com.study.doubanbook_for_android.business.DoubanBusiness.java
com.study.doubanbook_for_android.callback.AsynCallback.java
com.study.doubanbook_for_android.imagedownloader.FileCache.java
com.study.doubanbook_for_android.imagedownloader.INetImageDownloader.java
com.study.doubanbook_for_android.imagedownloader.ImageCache.java
com.study.doubanbook_for_android.imagedownloader.ImageDownloaderListener.java
com.study.doubanbook_for_android.imagedownloader.ImageDownloader.java
com.study.doubanbook_for_android.model.Annotations.java
com.study.doubanbook_for_android.model.AuthorUser.java
com.study.doubanbook_for_android.model.BookItem.java
com.study.doubanbook_for_android.model.CollectBookMsg.java
com.study.doubanbook_for_android.model.CollectSuccessResult.java
com.study.doubanbook_for_android.model.CommentItem.java
com.study.doubanbook_for_android.model.Comment.java
com.study.doubanbook_for_android.model.CurrenUserCollection.java
com.study.doubanbook_for_android.model.GeneralNoteResult.java
com.study.doubanbook_for_android.model.GeneralResult.java
com.study.doubanbook_for_android.model.GeneralUserResult.java
com.study.doubanbook_for_android.model.ImageItem.java
com.study.doubanbook_for_android.model.Rating.java
com.study.doubanbook_for_android.model.RequestGrantScope.java
com.study.doubanbook_for_android.model.TagItem.java
com.study.doubanbook_for_android.model.URLMananeger.java
com.study.doubanbook_for_android.utils.EncodeUtils.java
com.study.doubanbook_for_android.utils.JsonParser.java
com.study.doubanbook_for_android.utils.JsonUtil.java
com.study.doubanbook_for_android.utils.UriUtils.java