Back to project page doubanbook4android.
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.
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; } }