Java tutorial
/* * Copyright (C) 2009 Teleca Poland Sp. z o.o. <android@teleca.com> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.suning.mobile.ebuy.lottery.network.util; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.lang.ref.WeakReference; import java.net.SocketTimeoutException; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Locale; import javax.net.ssl.SSLHandshakeException; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.NameValuePair; import org.apache.http.NoHttpResponseException; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.CookieStore; import org.apache.http.client.HttpRequestRetryHandler; import org.apache.http.client.ResponseHandler; 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.client.utils.URLEncodedUtils; import org.apache.http.cookie.Cookie; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; import org.json.JSONException; import org.json.JSONObject; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import android.text.TextUtils; import android.util.Log; import android.webkit.CookieManager; import android.webkit.CookieSyncManager; import com.suning.mobile.ebuy.R; import com.suning.mobile.ebuy.SuningEBuyApplication; import com.suning.mobile.ebuy.lottery.config.LotteryConstants; import com.suning.mobile.ebuy.lottery.model.NetworkBean; import com.suning.mobile.ebuy.lottery.network.LotteryApiConfig; import com.suning.mobile.ebuy.lottery.utils.LogUtil; /** * get post * * @Title: * @Description: * @Author:12050514 wangwt * @Since:2012-12-14 * @Version: */ public class Caller { /** * Cache for most recent request */ private static RequestCache mRequestCache = null; /** * TAG */ private static final String TAG = "Caller"; /** * Https */ private boolean isHttpsRequest; /** * DefaultHttpClient, */ private final DefaultHttpClient mClient; /** * */ private SuningEBuyApplication mApplication; /** * https */ public void setHttpsRequestOpen() { isHttpsRequest = true; } /** * init caller */ public Caller() { mApplication = SuningEBuyApplication.getApp(); mClient = LotteryHttpClient.createHttpClient(); mClient.setHttpRequestRetryHandler(requestRetryHandler); } /** * * @Description: * @Author 12061235 * @Date 2013-5-17 */ public void setCookieStore(CookieStore cookieStore) { mClient.setCookieStore(cookieStore); } /** * * @Description: * @Author 12061235 * @Date 2013-5-17 */ public CookieStore getCookieStore() { return mClient.getCookieStore(); } /*** * post * * @param list * @return * @throws ClientProtocolException * @throws IOException */ public NetworkBean post(HttpEntity entity, String action) { NetworkBean subean = new NetworkBean(); String url = getTempUrl() + action; HttpPost request = new HttpPost(url); LogUtil.d("http post url", url); request.addHeader("Accept-Encoding", "gzip"); request.setEntity(entity); String result = ""; try { mClient.setCookieStore(SuningEBuyApplication.getInstance().getCookieStore()); result = mClient.execute(request, responseHandler); LogUtil.d("http post result", result); subean = parseStringToSuBean(subean, result); } catch (SocketTimeoutException e) { LogUtil.logException(e); subean.setResult(LotteryConstants.RESULT2); subean.setMessage(""); } catch (ClientProtocolException e) { LogUtil.logException(e); subean.setResult(LotteryConstants.RESULT2); subean.setMessage(mApplication.getResources().getString(R.string.cp_lottery_networkerror)); } catch (IOException e) { LogUtil.logException(e); subean.setResult(LotteryConstants.RESULT2); subean.setMessage(mApplication.getResources().getString(R.string.cp_lottery_networkerror)); } catch (NullPointerException e) { LogUtil.logException(e); } if (TextUtils.isEmpty(result)) { subean.setResult(LotteryConstants.RESULT2); subean.setMessage(mApplication.getResources().getString(R.string.cp_lottery_networkerror)); } return subean; } /** * * @Description:post * @Author 11076392 * @Date 2012-12-18 */ public NetworkBean post(List<NameValuePair> olist, String action) throws ClientProtocolException, IOException { List<NameValuePair> list = new ArrayList<NameValuePair>(); if (olist != null) { list.addAll(olist); } list.add(new BasicNameValuePair("dcode", mApplication.getDeviceId())); list.add(new BasicNameValuePair("versionCode", String.valueOf(mApplication.getVersionCode()))); return post(new UrlEncodedFormEntity(list, LotteryApiConfig.ENCODE), action); } /** * * @Description:get requestCache * @Author 12050514 wangwt * @Date 2013-1-7 */ public NetworkBean getWithoutCache(List<NameValuePair> list, String action) { return get(list, action, false); } /** * get requestCache;cachegetWithoutCache() * * @Description: * @Author 11076392 * @Date 2012-12-14 */ public NetworkBean get(List<NameValuePair> list, String action) { return get(list, action, true); } /** * url * * @Description: * @Author 12050514 wangwt * @Date 2013-1-10 */ public void setUrlTtlLong() { if (mRequestCache != null) { mRequestCache.setTtlLong(); } } /** * url * * @Description: * @Author 12050514 wangwt * @Date 2013-1-10 */ public void setUrlTtlShort() { if (mRequestCache != null) { mRequestCache.setTtlShort(); } } /** * * @Description: * @Author 12050514 wangwt * @Date 2013-1-7 */ private NetworkBean get(List<NameValuePair> list, String action, boolean withCache) { NetworkBean subean = new NetworkBean(); list.add(new BasicNameValuePair("dcode", mApplication.getDeviceId())); list.add(new BasicNameValuePair("versionCode", String.valueOf(mApplication.getVersionCode()))); String tempUrl = getTempUrl(); String result = null; String url = tempUrl + action + "?" + URLEncodedUtils.format(list, LotteryApiConfig.ENCODE); if (mRequestCache != null && withCache) { result = mRequestCache.get(url); } if (result != null) { Log.d(TAG, "Caller.get [cached] " + url); subean = parseStringToSuBean(subean, result); } else { HttpGet request = new HttpGet(url); // request.addHeader("Accept-Encoding", "gzip"); LogUtil.d("http url", request.getURI().toString()); try { mClient.setCookieStore(SuningEBuyApplication.getInstance().getCookieStore()); HttpResponse response = mClient.execute(request); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); if (entity != null) { Header header = entity.getContentEncoding(); if (header != null) { String contentEncoding = header.getValue(); if (contentEncoding != null) { if (contentEncoding.contains("gzip")) { entity = new GzipDecompressingEntity(entity); } } } String charset = EntityUtils.getContentCharSet(entity) == null ? LotteryApiConfig.ENCODE : EntityUtils.getContentCharSet(entity); result = new String(EntityUtils.toByteArray(entity), charset); subean = parseStringToSuBean(subean, result); } } else { subean.setResult(2); subean.setMessage(mApplication.getResources().getString(R.string.cp_lottery_networkerror)); } } catch (ClientProtocolException e) { LogUtil.logException(e); subean.setResult(2); subean.setMessage(mApplication.getResources().getString(R.string.cp_lottery_networkerror)); } catch (IOException e) { LogUtil.logException(e); subean.setResult(2); subean.setMessage(mApplication.getResources().getString(R.string.cp_lottery_networkerror)); } catch (NullPointerException e) { LogUtil.logException(e); } finally { if (mRequestCache != null && withCache && subean.getResult() == 0) { // mRequestCache.put(url, result); } } } if (result != null) { LogUtil.d("http result", result); } return subean; } private String getTempUrl() { String tempUrl = isHttpsRequest ? LotteryApiConfig.httpsUrl : LotteryApiConfig.url; if (isHttpsRequest) { isHttpsRequest = false; } return tempUrl; } /** * * @Description:get * @Author 12120153 * @Date 2013-1-3 */ public String getEbuy(String url, List<NameValuePair> list, String action) { LogUtil.e("url:" + url + action + "?" + URLEncodedUtils.format(list, LotteryApiConfig.ENCODE)); HttpGet request = new HttpGet(url + action + "?" + URLEncodedUtils.format(list, LotteryApiConfig.ENCODE)); request.addHeader("Accept-Encoding", "gzip"); request.addHeader("User-Agent", "Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) " + "AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16"); String result = ""; try { result = mClient.execute(request, responseHandler); } catch (NullPointerException e) { LogUtil.logException(e); result = ""; } catch (ClientProtocolException e) { LogUtil.logException(e); result = ""; } catch (IOException e) { LogUtil.logException(e); result = ""; } catch (Exception e) { LogUtil.logException(e); result = ""; } if (null == result) { result = ""; } return result; } /** * @Description:post * @Author 12120153 * @Date 2013-1-3 */ public String postEbuy(String url, List<NameValuePair> list, String action) { String result = ""; HttpEntity entity = null; try { entity = new UrlEncodedFormEntity(list, LotteryApiConfig.ENCODE); } catch (UnsupportedEncodingException e) { LogUtil.logException(e); return result; } LogUtil.d("http post url", url + action); HttpPost request = new HttpPost(url + action); request.addHeader("Accept-Encoding", "gzip"); request.setEntity(entity); try { result = mClient.execute(request, responseHandler); } catch (Exception e) { LogUtil.logException(e); } if (null == result) { result = ""; } return result; } /** * * @Description:SuBean * @Author 11076392 * @Date 2012-12-18 */ private NetworkBean parseStringToSuBean(NetworkBean subean, String result) { try { if (TextUtils.isEmpty(result)) { return subean; } JSONObject json = new JSONObject(result); if (json.has("xml")) { JSONObject jsonXml = json.getJSONObject("xml"); if (null != jsonXml && jsonXml.has("@errorCode")) { subean.setErrorCode(jsonXml.getString("@errorCode")); } } if (json.has("@desc")) { subean.setMessage(json.getString("@desc")); } if (json.has("@code")) { subean.setResult(json.getInt("@code")); } if (json.has("@date")) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA); try { subean.setDate(dateFormat.parse(json.getString("@date"))); mApplication.setDate(dateFormat.parse(json.getString("@date"))); synchronized (this) { mBase = mApplication.getDate().getTime(); } if (isFirst) { updateRunning(); } } catch (ParseException e) { LogUtil.logException(e); } } // if ("common.2.userNotLoggedIn".equals(subean.getErrorCode()) || "common.2.userMultiLoggedIn".equals(subean.getErrorCode())) { mApplication.resetUserBean(); subean.setResult(NetworkBean.RESULT_CODE); } subean.setJson(json); } catch (JSONException e) { LogUtil.logException(e); subean.setResult(2); subean.setMessage(""); } return subean; } /** * , HttpRequestRetryHandler */ private HttpRequestRetryHandler requestRetryHandler = new HttpRequestRetryHandler() { // public boolean retryRequest(IOException exception, int executionCount, HttpContext context) { // 3 if (executionCount >= LotteryApiConfig.MAXRETRIES) { // Do not retry if over max retry count return false; } if (exception instanceof NoHttpResponseException) { // Retry if the server dropped connection on us return true; } if (exception instanceof IOException) { return true; } if (exception instanceof SSLHandshakeException) { // Do not retry on SSL handshake exception return false; } HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); boolean idempotent = (request instanceof HttpEntityEnclosingRequest); if (!idempotent) { // Retry if the request is considered idempotent return true; } return false; } }; /** * ResponseHandlerHttpClientResponseHandler */ private ResponseHandler<String> responseHandler = new ResponseHandler<String>() { /** * */ public String handleResponse(HttpResponse response) throws ClientProtocolException, IOException { if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { HttpEntity entity = response.getEntity(); if (entity != null) { Header header = entity.getContentEncoding(); if (header != null) { String contentEncoding = header.getValue(); if (contentEncoding != null) { if (contentEncoding.contains("gzip")) { entity = new GzipDecompressingEntity(entity); } } } String charset = EntityUtils.getContentCharSet(entity) == null ? LotteryApiConfig.ENCODE : EntityUtils.getContentCharSet(entity); return new String(EntityUtils.toByteArray(entity), charset); } else { return null; } } else { return null; } } }; /** * * * @Description: * @Author:12072565 * @Date 2013-4-25 */ public static void setRequestCache(RequestCache requestCache) { Caller.mRequestCache = requestCache; } private long timeFirst; private long timeSecond; private long mBase; private boolean isFirst = true; private Handler mHandler = new IncomingHandler(this); /** * * @Description: * @Author:12072565 * @Date 2013-5-6 * @return void */ private void updateRunning() { isFirst = false; timeFirst = SystemClock.elapsedRealtime(); mHandler.sendMessageDelayed(Message.obtain(mHandler, 2), 1000); } /** * * @Title:handler static WeakReference * @Description: * @Author:12072565 * @Since:2013-5-6 * @Version: */ private static class IncomingHandler extends Handler { private final WeakReference<Caller> mClass; IncomingHandler(Caller className) { mClass = new WeakReference<Caller>(className); } @Override public void handleMessage(Message msg) { Caller className = mClass.get(); if (className != null) { className.handleMessage(msg); } } } /** * * @Description: handleMessage * @param m * @Author:12072565 * @Date 2013-5-6 * @return void */ private void handleMessage(Message m) { if (m.what == 2) { timeSecond = SystemClock.elapsedRealtime(); updateDate(Math.abs(timeSecond - timeFirst)); mHandler.sendMessageDelayed(Message.obtain(mHandler, 2), 1000); } } /** * * @Description: * @param des * @Author:12072565 * @Date 2013-5-6 * @return void */ private synchronized void updateDate(long des) { timeFirst = SystemClock.elapsedRealtime(); mBase = mBase + des; SuningEBuyApplication.getApp().setDate(new Date(mBase)); } /** * webviewcookie */ public void syncCookie() { List<Cookie> cookies = mClient.getCookieStore().getCookies(); if (!cookies.isEmpty()) { CookieSyncManager cookieSyncManager = CookieSyncManager.createInstance(mApplication); CookieManager cookieManager = CookieManager.getInstance(); for (Cookie cookie : cookies) { String domain = cookie.getDomain(); String strCookies = cookie.getName() + "=" + cookie.getValue() + "; domain=" + domain; cookieManager.setCookie(domain, strCookies); cookieSyncManager.sync(); } } } }