├── res ├── raw │ ├── aaa.json │ ├── bbb.json │ └── ccc.json ├── drawable-hdpi │ └── ic_launcher.png ├── drawable-mdpi │ └── ic_launcher.png ├── drawable-xhdpi │ └── ic_launcher.png ├── drawable-xxhdpi │ └── ic_launcher.png ├── values │ ├── dimens.xml │ ├── sql.xml │ ├── styles.xml │ └── strings.xml ├── menu │ └── main.xml └── layout │ ├── activity_main.xml │ └── dialog_progress.xml ├── ic_launcher-web.png ├── src └── com │ └── vic │ └── http │ ├── entity │ ├── Login.java │ ├── Menu.java │ ├── Store.java │ ├── HttpHead.java │ └── Index.java │ ├── http │ ├── ObserverCallBack.java │ ├── HttpRequest.java │ ├── AnsynHttpRequest.java │ └── AnsynHttpRequestV2.java │ ├── utils │ ├── MapData.java │ ├── Md5Utils.java │ ├── Encoder.java │ ├── TimeCompare.java │ ├── Network.java │ ├── ThreadPoolUtils.java │ └── Log.java │ ├── app │ ├── MainActivity.java │ └── BaseActivity.java │ ├── common │ └── C.java │ └── db │ └── DBHelper.java ├── .gitignore ├── .classpath ├── project.properties ├── proguard-project.txt ├── .project ├── LICENSE ├── README.md └── AndroidManifest.xml /res/raw/aaa.json: -------------------------------------------------------------------------------- 1 | { 2 | aa:[{"aa":"关注喔唷"},"bb":"我是数据",cc:"❦-平常心"}] 3 | } -------------------------------------------------------------------------------- /res/raw/bbb.json: -------------------------------------------------------------------------------- 1 | { 2 | aa:[{"aa":"网络情"}"bb":"aaad",cc:"❦-平常心",dd:"回复"}] 3 | } -------------------------------------------------------------------------------- /ic_launcher-web.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pcxin/android_http_ansyn_packaging/HEAD/ic_launcher-web.png -------------------------------------------------------------------------------- /res/drawable-hdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pcxin/android_http_ansyn_packaging/HEAD/res/drawable-hdpi/ic_launcher.png -------------------------------------------------------------------------------- /res/drawable-mdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pcxin/android_http_ansyn_packaging/HEAD/res/drawable-mdpi/ic_launcher.png -------------------------------------------------------------------------------- /res/drawable-xhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pcxin/android_http_ansyn_packaging/HEAD/res/drawable-xhdpi/ic_launcher.png -------------------------------------------------------------------------------- /src/com/vic/http/entity/Login.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pcxin/android_http_ansyn_packaging/HEAD/src/com/vic/http/entity/Login.java -------------------------------------------------------------------------------- /src/com/vic/http/entity/Menu.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pcxin/android_http_ansyn_packaging/HEAD/src/com/vic/http/entity/Menu.java -------------------------------------------------------------------------------- /src/com/vic/http/entity/Store.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pcxin/android_http_ansyn_packaging/HEAD/src/com/vic/http/entity/Store.java -------------------------------------------------------------------------------- /res/drawable-xxhdpi/ic_launcher.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pcxin/android_http_ansyn_packaging/HEAD/res/drawable-xxhdpi/ic_launcher.png -------------------------------------------------------------------------------- /res/raw/ccc.json: -------------------------------------------------------------------------------- 1 | { 2 | aa:[{"aa":"打分法情"}"bb":"是电风扇的",cc:"❦-平常心",dd:"似懂非懂是复"}], 3 | bb:[{"aaa":"打分法情"}"bbb":"是电风扇的",ccc:"❦-平常心",ddd:"似懂非懂是复"}] 4 | } -------------------------------------------------------------------------------- /src/com/vic/http/entity/HttpHead.java: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pcxin/android_http_ansyn_packaging/HEAD/src/com/vic/http/entity/HttpHead.java -------------------------------------------------------------------------------- /src/com/vic/http/http/ObserverCallBack.java: -------------------------------------------------------------------------------- 1 | package com.vic.http.http; 2 | public interface ObserverCallBack{ 3 | public void back(String data, int url); 4 | } -------------------------------------------------------------------------------- /res/values/dimens.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 16dp 5 | 16dp 6 | 7 | 8 | -------------------------------------------------------------------------------- /res/menu/main.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /res/values/sql.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | CREATE TABLE IF NOT EXISTS cacheUrlData(url TEXT PRIMARY KEY, cacheData TEXT, createTime TEXT) 6 | 7 | 8 | 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Built application files 2 | *.apk 3 | *.ap_ 4 | 5 | # Files for the Dalvik VM 6 | *.dex 7 | 8 | # Java class files 9 | *.class 10 | 11 | # Generated files 12 | bin/ 13 | gen/ 14 | 15 | # Gradle files 16 | .gradle/ 17 | build/ 18 | 19 | # Local configuration file (sdk path, etc) 20 | local.properties 21 | 22 | # Proguard folder generated by Eclipse 23 | proguard/ 24 | 25 | # mac os 26 | .DS_Store 27 | -------------------------------------------------------------------------------- /.classpath: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | -------------------------------------------------------------------------------- /project.properties: -------------------------------------------------------------------------------- 1 | # This file is automatically generated by Android Tools. 2 | # Do not modify this file -- YOUR CHANGES WILL BE ERASED! 3 | # 4 | # This file must be checked in Version Control Systems. 5 | # 6 | # To customize properties used by the Ant build system edit 7 | # "ant.properties", and override values to adapt the script to your 8 | # project structure. 9 | # 10 | # To enable ProGuard to shrink and obfuscate your code, uncomment this (available properties: sdk.dir, user.home): 11 | #proguard.config=${sdk.dir}/tools/proguard/proguard-android.txt:proguard-project.txt 12 | 13 | # Project target. 14 | target=android-17 15 | -------------------------------------------------------------------------------- /res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 10 | 11 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /res/values/styles.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 7 | 14 | 15 | 16 | 19 | 20 | 21 | -------------------------------------------------------------------------------- /proguard-project.txt: -------------------------------------------------------------------------------- 1 | # To enable ProGuard in your project, edit project.properties 2 | # to define the proguard.config property as described in that file. 3 | # 4 | # Add project specific ProGuard rules here. 5 | # By default, the flags in this file are appended to flags specified 6 | # in ${sdk.dir}/tools/proguard/proguard-android.txt 7 | # You can edit the include path and order by changing the ProGuard 8 | # include property in project.properties. 9 | # 10 | # For more details, see 11 | # http://developer.android.com/guide/developing/tools/proguard.html 12 | 13 | # Add any project specific keep options here: 14 | 15 | # If your project uses WebView with JS, uncomment the following 16 | # and specify the fully qualified class name to the JavaScript interface 17 | # class: 18 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 19 | # public *; 20 | #} 21 | -------------------------------------------------------------------------------- /res/layout/dialog_progress.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 14 | 15 | 23 | 24 | -------------------------------------------------------------------------------- /.project: -------------------------------------------------------------------------------- 1 | 2 | 3 | HTTP 4 | 5 | 6 | 7 | 8 | 9 | com.android.ide.eclipse.adt.ResourceManagerBuilder 10 | 11 | 12 | 13 | 14 | com.android.ide.eclipse.adt.PreCompilerBuilder 15 | 16 | 17 | 18 | 19 | org.eclipse.jdt.core.javabuilder 20 | 21 | 22 | 23 | 24 | com.android.ide.eclipse.adt.ApkBuilder 25 | 26 | 27 | 28 | 29 | 30 | com.android.ide.eclipse.adt.AndroidNature 31 | org.eclipse.jdt.core.javanature 32 | 33 | 34 | -------------------------------------------------------------------------------- /src/com/vic/http/utils/MapData.java: -------------------------------------------------------------------------------- 1 | package com.vic.http.utils; 2 | 3 | import java.util.Map; 4 | 5 | import android.content.Context; 6 | 7 | public class MapData { 8 | public Map addData(Map map, Context context){ 9 | // if(App.index != null){ 10 | // map.put("user_id", App.index.user_id); 11 | // map.put("device_id", App.index.device_id); 12 | // map.put("encrypt", App.index.encrypt); 13 | // map.put("username", LoginActivity.getCacheByKey(context, "username", "")); 14 | // } 15 | // map.put("password", LoginActivity.getCacheByKey(context, "password", "")); 16 | // map.put("device_mac", PhoneInfo.getWifiInfo(context).getMacAddress()); 17 | // map.put("device_imei", PhoneInfo.getIMEI(context)); 18 | // map.put("device_type", Build.MODEL); 19 | // map.put("client_type", C.client.CType); 20 | // map.put("client_version", PhoneInfo.getVersion(context)); 21 | // map.put("last_loginip", PhoneInfo.getHostIpAddress()); 22 | return map; 23 | } 24 | } -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 pingchangxin 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/com/vic/http/utils/Md5Utils.java: -------------------------------------------------------------------------------- 1 | package com.vic.http.utils; 2 | 3 | import java.security.MessageDigest; 4 | import java.security.NoSuchAlgorithmException; 5 | 6 | public class Md5Utils { 7 | private static final char HEX_DIGITS[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}; 8 | 9 | public static String toHexString(byte[] b) { 10 | 11 | //String to byte 12 | StringBuilder sb = new StringBuilder(b.length * 2); 13 | 14 | for (int i = 0; i < b.length; i++) { 15 | sb.append(HEX_DIGITS[(b[i] & 0xf0) >>> 4]); 16 | sb.append(HEX_DIGITS[b[i] & 0x0f]); 17 | } 18 | 19 | return sb.toString(); 20 | } 21 | 22 | public String md5(String s) { 23 | 24 | try { 25 | // Create MD5 Hash 26 | MessageDigest digest = java.security.MessageDigest.getInstance("MD5"); 27 | digest.update(s.getBytes()); 28 | byte messageDigest[] = digest.digest(); 29 | return toHexString(messageDigest); 30 | } catch (NoSuchAlgorithmException e) { 31 | e.printStackTrace(); 32 | } 33 | return ""; 34 | } 35 | } -------------------------------------------------------------------------------- /src/com/vic/http/utils/Encoder.java: -------------------------------------------------------------------------------- 1 | package com.vic.http.utils; 2 | 3 | import java.io.UnsupportedEncodingException; 4 | import java.net.URLEncoder; 5 | 6 | public class Encoder { 7 | /** 8 | * @param value 9 | * string to be encoded 10 | * @return encoded parameters string 11 | */ 12 | public static String encode(String value) { 13 | String encoded = null; 14 | try { 15 | encoded = URLEncoder.encode(value, "UTF-8"); 16 | } catch (UnsupportedEncodingException ignore) { 17 | } 18 | StringBuffer buf = new StringBuffer(encoded.length()); 19 | char focus; 20 | for (int i = 0; i < encoded.length(); i++) { 21 | focus = encoded.charAt(i); 22 | if (focus == '*') { 23 | buf.append("%2A"); 24 | } else if (focus == '+') { 25 | buf.append("%20"); 26 | } else if (focus == '%' && (i + 1) < encoded.length() && encoded.charAt(i + 1) == '7' 27 | && encoded.charAt(i + 2) == 'E') { 28 | buf.append('~'); 29 | i += 2; 30 | } else { 31 | buf.append(focus); 32 | } 33 | } 34 | return buf.toString(); 35 | } 36 | } 37 | 38 | -------------------------------------------------------------------------------- /res/values/strings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | HTTP 5 | Settings 6 | Hello world! 7 | 8 | 9 | 确定 10 | 取消 11 | 12 | 没有可用网络 13 | 是否对网络进行设置? 14 | 设置 15 | 离开 16 | 网络异常! 17 | 无网络连接! 18 | 19 | 获取数据失败 20 | 网络超时,服务器断开或者请检查网络连接是否正常 21 | 暂无数据 22 | 获取用户信息失败 23 | 24 | 正在加载,请稍后… 25 | 正在验证数据,请稍后… 26 | 正在提交,请稍后… 27 | no image data! 28 | 29 | 30 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | android_http_ansyn_packaging 2 | ============================ 3 | 4 | my blog article -> http://blog.csdn.net/vpingchangxin/article/details/23375461 5 | 6 | android http ansyn packaging android http 7 | 8 | 本demo主要对异步请求封装 可用作基本项目框架来使用 9 | 网络请求等等小细节已经ok 如有需要请进一步更改 10 | 11 | 1)封装HttpClient 12 | 13 | 2)由于用到线程池,可以进行多任务网络请求操作 14 | 15 | 3)没有网络的时候进行网络状态检查 16 | 17 | 4)对请求的数据根据URL进行缓存到本地sqlite数据库中(我刚刚想起了 post请求的时候需要对缓存url及本地数据存取做修改才可以正常用 如果不想进行修改可以用get形式) 18 | 19 | 5)本demo可以直接运行 本来想测试protobuf进行数据处理的 要放在github上就改成json了(entity中有简单的xml解析:Menu.java 其他的都是json的 json 也可用Gson更方便) 20 | 21 | The demo is mainly used as a basic package for asynchronous requests to use the framework of the project 22 | Network requests, and so little detail has been ok if necessary further changes 23 | 24 | 1) Package HttpClient 25 | 26 | 2) Due to use thread pool, you can multi-task operating a network request 27 | 28 | 3) when the network is no network status check 29 | 30 | 4) According to the data of the requested URL is cached to the local sqlite database (I just think it needs to post requests to the cache url and local data access to make changes before they can be modified if you do not normally use can get the form) 31 | 32 | 5) The demo can be run directly protobuf had wanted to test the data processing to be placed on github into json on the (entity has simple xml parsing: Menu.java others are also available Gson json json's more convenient) 33 | -------------------------------------------------------------------------------- /src/com/vic/http/utils/TimeCompare.java: -------------------------------------------------------------------------------- 1 | package com.vic.http.utils; 2 | 3 | import java.text.DateFormat; 4 | import java.text.SimpleDateFormat; 5 | import java.util.Date; 6 | 7 | /** 8 | * 9 | * 时间差 10 | * @author chen 11 | * 12 | */ 13 | public class TimeCompare { 14 | 15 | /** 小时 */ 16 | private static final int hour = 1000 * 60 * 60; 17 | // private static final int hour = 1000 * 60; 18 | /** 19 | * 支持 yyyy-MM-dd HH精确到小时 20 | * @param start 开始时间 if:2012-2-10 11 21 | * @param end 结束时间 if:2012-02-11 13:12:21 22 | * @return 小时数 23 | */ 24 | public static int compareHourTime(String start,String end){ 25 | DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm"); 26 | 27 | try { 28 | Date d1 = df.parse(end); 29 | Date d2 = df.parse(start); 30 | long diff = d1.getTime() - d2.getTime(); 31 | int hours = (int)(diff / hour); 32 | return hours; 33 | } catch (Exception e) { 34 | } 35 | return 0; 36 | } 37 | 38 | /** 39 | * 根据当前时间 获取时间差 支持 yyyy-MM-dd HH精确到小时 40 | * @param start 开始时间 if:2012-2-10 11 41 | * @return 小时数 42 | */ 43 | public static int compareHourTime(String start){ 44 | DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); 45 | 46 | try { 47 | Date d2 = sdf.parse(start); 48 | long diff = System.currentTimeMillis() - d2.getTime(); 49 | int hours = (int)(diff / hour); 50 | return hours; 51 | } catch (Exception e) { 52 | } 53 | return 0; 54 | } 55 | } -------------------------------------------------------------------------------- /src/com/vic/http/utils/Network.java: -------------------------------------------------------------------------------- 1 | package com.vic.http.utils; 2 | 3 | import android.content.Context; 4 | import android.net.ConnectivityManager; 5 | import android.net.NetworkInfo; 6 | 7 | /** 8 | * 9 | * 检测网络 10 | * @author Administrator 11 | * 12 | */ 13 | public class Network { 14 | 15 | /** 网络不可用 */ 16 | public static final int NONETWORK= 0; 17 | /** 是wifi连接 */ 18 | public static final int WIFI = 1; 19 | /** 不是wifi连接 */ 20 | public static final int NOWIFI = 2; 21 | 22 | /** 23 | * 检验网络连接 并判断是否是wifi连接 24 | * @param context 25 | * @return
  • 没有网络:Network.NONETWORK;
  • wifi 连接:Network.WIFI;
  • mobile 连接:Network.NOWIFI
  • 26 | */ 27 | public static int checkNetWorkType(Context context) { 28 | 29 | if (!checkNetWork(context)) { 30 | return Network.NONETWORK; 31 | } 32 | ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 33 | // cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); 34 | if (cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting()) 35 | return Network.WIFI; 36 | else 37 | return Network.NOWIFI; 38 | } 39 | 40 | /** 41 | * 检测网络是否连接 42 | * @param context 43 | * @return 44 | */ 45 | public static boolean checkNetWork(Context context){ 46 | // 1.获得连接设备管理器 47 | ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 48 | if(cm == null){ 49 | return false; 50 | } 51 | NetworkInfo ni = cm.getActiveNetworkInfo(); 52 | if(ni == null || !ni.isAvailable()){ 53 | return false; 54 | } 55 | return true; 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /src/com/vic/http/utils/ThreadPoolUtils.java: -------------------------------------------------------------------------------- 1 | package com.vic.http.utils; 2 | 3 | import java.util.concurrent.ArrayBlockingQueue; 4 | import java.util.concurrent.BlockingQueue; 5 | import java.util.concurrent.ThreadFactory; 6 | import java.util.concurrent.ThreadPoolExecutor; 7 | import java.util.concurrent.TimeUnit; 8 | import java.util.concurrent.atomic.AtomicInteger; 9 | 10 | /** 11 | * 线程池辅助类,整个应用程序就只有一个线程池去管理线程。 可以设置核心线程数、最大线程数、额外线程空状态生存时间,阻塞队列长度来优化线程池。 12 | * 下面的数据都是参考Android的AsynTask里的数据。 13 | * 14 | * @author zet 15 | * 16 | */ 17 | public class ThreadPoolUtils { 18 | 19 | private ThreadPoolUtils() { 20 | 21 | } 22 | 23 | // 线程池核心线程数 24 | private static int CORE_POOL_SIZE = 5; 25 | 26 | // 线程池最大线程数 27 | private static int MAX_POOL_SIZE = 100; 28 | 29 | // 额外线程空状态生存时间 30 | private static int KEEP_ALIVE_TIME = 10000; 31 | 32 | // 阻塞队列。当核心线程都被占用,且阻塞队列已满的情况下,才会开启额外线程。 33 | private static BlockingQueue workQueue = new ArrayBlockingQueue( 34 | 10); 35 | 36 | // 线程工厂 37 | private static ThreadFactory threadFactory = new ThreadFactory() { 38 | private final AtomicInteger integer = new AtomicInteger(); 39 | 40 | @Override 41 | public Thread newThread(Runnable r) { 42 | return new Thread(r, "myThreadPool thread:" 43 | + integer.getAndIncrement()); 44 | } 45 | }; 46 | 47 | // 线程池 48 | private static ThreadPoolExecutor threadPool; 49 | 50 | static { 51 | threadPool = new ThreadPoolExecutor(CORE_POOL_SIZE, MAX_POOL_SIZE, 52 | KEEP_ALIVE_TIME, TimeUnit.SECONDS, workQueue, threadFactory); 53 | } 54 | 55 | /** 56 | * 从线程池中抽取线程,执行指定的Runnable对象 57 | * 58 | * @param runnable 59 | */ 60 | public static void execute(Runnable runnable) { 61 | threadPool.execute(runnable); 62 | } 63 | 64 | } -------------------------------------------------------------------------------- /src/com/vic/http/http/HttpRequest.java: -------------------------------------------------------------------------------- 1 | package com.vic.http.http; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.InputStreamReader; 5 | import java.net.HttpURLConnection; 6 | import java.net.URL; 7 | 8 | import org.apache.http.HttpStatus; 9 | import org.apache.http.impl.client.DefaultHttpClient; 10 | 11 | /** 12 | * 异步数据请求 13 | * @author chen 14 | * @date 2012-10-25 下午2:57:33 15 | */ 16 | public class HttpRequest { 17 | 18 | public static final int REQUEST_TIMEOUT = 10*1000;//设置请求超时10秒钟 19 | public static final int SO_TIMEOUT = 10*1000; //设置等待数据超时时间10秒钟 20 | 21 | public DefaultHttpClient mHttpClient = null; 22 | public String doRequest(String path) throws Exception{ 23 | // BasicHttpParams httpParams = new BasicHttpParams(); 24 | // HttpConnectionParams.setConnectionTimeout(httpParams, REQUEST_TIMEOUT); 25 | // HttpConnectionParams.setSoTimeout(httpParams, SO_TIMEOUT); 26 | // Log.i("httpurl", url); 27 | //// if(mHttpClient == null) 28 | // mHttpClient = new DefaultHttpClient(httpParams); 29 | // HttpGet get = new HttpGet(url); 30 | // HttpResponse response = null; 31 | // response = mHttpClient.execute(get); 32 | // String data = null; 33 | 34 | URL url = new URL(path); 35 | HttpURLConnection urlConn = (HttpURLConnection) url.openConnection(); 36 | urlConn.setConnectTimeout(5 * 1000); 37 | urlConn.connect(); 38 | BufferedReader buffer = null; 39 | String line = null; 40 | StringBuffer sb = new StringBuffer(); 41 | if (urlConn.getResponseCode() == HttpStatus.SC_OK) { 42 | 43 | buffer = new BufferedReader(new InputStreamReader(urlConn.getInputStream())); 44 | while ((line = buffer.readLine()) != null) { 45 | sb.append(line); 46 | } 47 | return sb.toString(); 48 | } else { 49 | return null; 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 37 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /src/com/vic/http/entity/Index.java: -------------------------------------------------------------------------------- 1 | package com.vic.http.entity; 2 | 3 | import java.io.Serializable; 4 | import java.lang.reflect.Field; 5 | 6 | import org.json.JSONException; 7 | import org.json.JSONObject; 8 | 9 | import android.content.Context; 10 | 11 | public class Index implements Serializable{ 12 | 13 | /** 14 | * @Fields serialVersionUID : 15 | */ 16 | private static final long serialVersionUID = 1L; 17 | 18 | public String upgrade; 19 | public String forAudit; 20 | public String request; 21 | public String current_time; 22 | public String device_id; 23 | public String resultcode; 24 | public String download_addr; 25 | public String qq; 26 | public String alertMsg; 27 | public HttpHead httpHead; 28 | 29 | // else static 30 | public String encrypt; 31 | public String user_id = "1"; 32 | public boolean is501 = false; 33 | public boolean is502 = false; 34 | /** 35 | * @Description: 36 | * @author vic 37 | * @param context 38 | * @param data 39 | * @param isCache 40 | * @return 41 | */ 42 | public Index convertHttpHead(Context context,String data){ 43 | String tempItem = null; 44 | try { 45 | Field[] fields = this.getClass().getDeclaredFields(); 46 | JSONObject jsonObject = new JSONObject(data); 47 | for (int j = 0; j < fields.length; j++) { 48 | Field field = fields[j]; 49 | try { 50 | tempItem = fields[j].getName(); 51 | if(tempItem.equals("serialVersionUID") || jsonObject.isNull(tempItem) || jsonObject.get(tempItem) == JSONObject.NULL) continue; 52 | if(tempItem.equals("request")){ 53 | this.httpHead = new HttpHead().convertHttpHead(context, jsonObject.get(tempItem).toString()); 54 | continue; 55 | } 56 | field.set(this, jsonObject.get(tempItem).toString()); 57 | 58 | } catch (Exception e) { 59 | e.printStackTrace(); 60 | } 61 | } 62 | } catch (JSONException e) { 63 | e.printStackTrace(); 64 | } 65 | return this; 66 | } 67 | 68 | @Override 69 | public String toString() { 70 | return "Index [upgrade=" + upgrade + ", forAudit=" + forAudit 71 | + ", current_time=" + current_time 72 | + ", device_id=" + device_id + ", resultcode=" + resultcode 73 | + ", download_addr=" + download_addr + ", qq=" + qq 74 | + ", httpHead=" + httpHead + "]"; 75 | } 76 | 77 | } 78 | -------------------------------------------------------------------------------- /src/com/vic/http/app/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.vic.http.app; 2 | 3 | import java.util.HashMap; 4 | 5 | import android.content.Intent; 6 | import android.os.Bundle; 7 | import android.os.Handler; 8 | import android.os.Message; 9 | import android.widget.Toast; 10 | 11 | import com.vic.http.common.C; 12 | import com.vic.http.http.AnsynHttpRequest; 13 | import com.vic.http.http.AnsynHttpRequestV2; 14 | import com.vic.http.http.ObserverCallBack; 15 | import com.vic.http.utils.MapData; 16 | 17 | public class MainActivity extends BaseActivity { 18 | 19 | @Override 20 | public void onCreate(Bundle savedInstanceState) { 21 | super.onCreate(savedInstanceState); 22 | setContentView(R.layout.activity_main); 23 | 24 | // by get 25 | map = new HashMap(); 26 | // map.put("method", "adv_list"); 27 | // map.put("regionid", "320200"); 28 | AnsynHttpRequest.requestByGet(context, callbackData, C.http.http_adv, map, true, true); 29 | 30 | // by post 31 | map = new HashMap(); 32 | map = new MapData().addData(map, context); 33 | AnsynHttpRequest.requestByPost(context, C.http.http_test_bb,callbackData, C.http.http_area, map, false, false); 34 | 35 | // http初始化 36 | map = new HashMap(); 37 | // map.put("method", "businesscategory_list"); 38 | AnsynHttpRequest.requestByPost(context, C.http.http_test_cc,callbackData, C.http.http_area, map, false, false); 39 | 40 | // v2 use ---------- best 41 | AnsynHttpRequestV2.requestByPost(context, C.http.http_test_cc,callbackDataV2, C.http.http_area, map, false, false); 42 | } 43 | 44 | /** 45 | * 异步回调回来并处理数据 46 | */ 47 | private ObserverCallBack callbackDataV2 = new ObserverCallBack(){ 48 | public void back(String data, int url) { 49 | switch (url) { 50 | case C.http.http_area: // 进行数据解析 51 | if(data == null) { 52 | return; 53 | } 54 | Toast.makeText(context, "测试数据 :"+data, Toast.LENGTH_SHORT).show(); 55 | break; 56 | default: 57 | Toast.makeText(context, "测试数据 数据编号:"+url, Toast.LENGTH_SHORT).show(); 58 | break; 59 | } 60 | } 61 | }; 62 | 63 | /** 64 | * 异步回调回来并处理数据 65 | */ 66 | private ObserverCallBack callbackData = new ObserverCallBack(){ 67 | public void back(String data, int url) { 68 | switch (url) { 69 | case C.http.http_area: // 进行数据解析 70 | if(data == null) { 71 | return; 72 | } 73 | try { 74 | // Index index = new Index(); 75 | // index = index.convertHttpHead(context,data); 76 | //// App.index = index; 77 | // Log.i(tag, index.toString()); 78 | Message msg = new Message(); 79 | msg.what = 1; 80 | // msg.obj = index; 81 | mHandler.sendMessage(msg); 82 | } catch (Exception e) { 83 | e.printStackTrace(); 84 | } 85 | break; 86 | default: 87 | Message msg = new Message(); 88 | msg.what = url; 89 | mHandler.sendMessage(msg); 90 | break; 91 | } 92 | } 93 | }; 94 | 95 | /** 96 | * 处理UI线程中数据 97 | */ 98 | private Handler mHandler = new Handler() { 99 | public void handleMessage(Message msg) { 100 | Intent intent = null; 101 | switch (msg.what) { 102 | case 1: 103 | Toast.makeText(context, "测试数据 数据编号:"+msg.what, Toast.LENGTH_SHORT).show(); 104 | break; 105 | case 2: 106 | break; 107 | case 3: 108 | break; 109 | case 4: 110 | break; 111 | case 5: 112 | break; 113 | case 6: 114 | break; 115 | case 7: 116 | // setListViewHeightBasedOnChildren(mListView); 117 | // setListViewHeightBasedOnChildren(mListView); 118 | break; 119 | case 8: 120 | // Bitmap bmp = (Bitmap)msg.obj; 121 | // SendMsg.weixin(context, mCategory, bmp); 122 | break; 123 | default: 124 | Toast.makeText(context, "测试数据 数据编号:"+msg.what, Toast.LENGTH_SHORT).show(); 125 | break; 126 | } 127 | }; 128 | }; 129 | } 130 | -------------------------------------------------------------------------------- /src/com/vic/http/common/C.java: -------------------------------------------------------------------------------- 1 | package com.vic.http.common; 2 | 3 | import java.util.Map; 4 | 5 | import android.content.Context; 6 | import android.content.SharedPreferences; 7 | import android.content.SharedPreferences.Editor; 8 | 9 | 10 | /** 11 | * 公共静态类 12 | * @author chen 13 | * @date 2012-10-25 下午3:13:44 14 | */ 15 | public final class C { 16 | /** 17 | * 显示屏信息 18 | * @author chen 19 | * @date 2012-10-25 下午3:15:23 20 | */ 21 | public static final class display { 22 | /** 屏幕分辨率宽度 */ 23 | public static int widthPixels = 0; 24 | /** 屏幕分辨率高度 */ 25 | public static int heightPixels = 0; 26 | 27 | /** 容器宽度 */ 28 | public static int contentWidth = 0; 29 | /** 容器高度 */ 30 | public static int contentHeight = 0; 31 | 32 | } 33 | 34 | /** 百度地图key */ 35 | public static final String MAP_BAIDU_KEY = "AC57AC62D5D7BE2A42218C33983A164E7B4C1666"; 36 | 37 | /** 微信key */ 38 | public static final String WEIXIN_APP_ID = "wx53384059ceb70d85"; 39 | /** 微信发图片大小 */ 40 | public static final int THUMB_SIZE = 150; 41 | 42 | /** 43 | * 分页信息 44 | * @author chen 45 | * @date 2012-11-8 下午1:44:36 46 | */ 47 | public static final class page { 48 | /** 每页数量 */ 49 | public static final int pageSize = 10; 50 | } 51 | 52 | /** google 统计前缀*/ 53 | public static final String GA_TITLE = "/Android/app/"; 54 | 55 | /** 56 | * 网络连接 57 | * @author chen 58 | * @date 2012-10-25 下午3:14:36 59 | */ 60 | public static final class http { 61 | /** 服务器地址 */ 62 | public static final String CType = "1"; 63 | public static final String CChannel = "dev"; 64 | public static boolean isInstall = false; 65 | public static final String http_request_head = "https://raw.githubusercontent.com/pcxin/android_http_ansyn_packaging/master/res/raw/aaa.json"; 66 | public static String http_img = ""; 67 | public static final String http_test_bb = "https://raw.githubusercontent.com/pcxin/android_http_ansyn_packaging/master/res/raw/bbb.json"; 68 | public static final String http_test_cc = "https://raw.githubusercontent.com/pcxin/android_http_ansyn_packaging/master/res/raw/ccc.json"; 69 | 70 | /*** http 标识配置 */ 71 | // public static final int http_area = "http_area".hashCode(); //待优化 72 | public static final int http_area = 0xffffff00; // 73 | public static final int http_menu = 0xffffff01; 74 | public static final int http_adv = 0xffffff02; 75 | 76 | 77 | /** 替换https 为http */ 78 | public static String httpPic(){ 79 | if(http_request_head.startsWith("https:")) return http_request_head.replaceAll("https:", "http:"); 80 | return http_request_head; 81 | } 82 | 83 | public static String joinUrl(Map map){ 84 | StringBuffer buffer = new StringBuffer(); 85 | buffer.append(C.http.http_request_head) 86 | // .append(context.getResources().getString(url)) 87 | .append("?"); 88 | if(map != null && map.size()>0) 89 | for (String key : map.keySet()) { 90 | buffer.append(key) 91 | .append("=") 92 | .append(map.get(key)) 93 | .append("&"); 94 | } 95 | String requestUrl = buffer.toString(); 96 | requestUrl = requestUrl.substring(0,requestUrl.length()-1); 97 | return requestUrl; 98 | } 99 | } 100 | public static final class message_title { 101 | public static final String success = "SUCCESS"; 102 | } 103 | public static final class cache{ 104 | public static final String PHONE114_AREA = "phone114_area"; 105 | public static final String CHECK_AREA = "check_area"; 106 | public static final String CHECK_AREA_TITLE = "check_area_title"; 107 | public static final String CHECK_FENLEI = "check_fenlei"; 108 | public static final String CHECK_YOUHUI = "check_youhui"; 109 | public static final String CHECK_WAIMAI = "check_waimai"; 110 | public static final String USER_NAME = "user_name"; 111 | public static final String USER_PWD = "user_pwd"; 112 | 113 | /** 114 | * @Description: 缓存数据 115 | * @author vic 116 | * @param key 117 | * @param value 118 | */ 119 | public static void saveCache(Context context, String key, String value) { 120 | SharedPreferences preferences = context.getSharedPreferences("cacheInfo", 121 | Context.MODE_PRIVATE); 122 | Editor editor = preferences.edit(); 123 | editor.putString(key, value); 124 | editor.commit(); 125 | } 126 | 127 | /** 128 | * @Description: 获取缓存数据 129 | * @author vic 130 | * @param key 131 | * @param defaultValue 132 | * @return 133 | */ 134 | public static String getCacheByKey(Context context, String key,String defaultValue) { 135 | SharedPreferences preferences = context.getSharedPreferences("cacheInfo", 136 | Context.MODE_PRIVATE); 137 | return preferences.getString(key, defaultValue); 138 | } 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /src/com/vic/http/utils/Log.java: -------------------------------------------------------------------------------- 1 | package com.vic.http.utils; 2 | 3 | import java.io.PrintWriter; 4 | import java.io.StringWriter; 5 | 6 | /** 7 | * 自定义Log输出 8 | * @author chen 9 | * @date 2012-8-30 下午2:57:23 10 | */ 11 | public class Log { 12 | 13 | /** 是否输出日志 */ 14 | public static final boolean ISPRINT = true; 15 | /** 返回值 */ 16 | private static final int RETURN = 6; 17 | 18 | private Log() { 19 | } 20 | 21 | /** 22 | * Send a {@link #android.util.Log.VERBOSE} log message. 23 | * @param tag Used to identify the source of a log message. It usually identifies 24 | * the class or activity where the log call occurs. 25 | * @param msg The message you would like logged. 26 | */ 27 | public static int v(String tag, String msg) { 28 | try { 29 | if (ISPRINT) 30 | return android.util.Log.v(tag, msg); 31 | } catch (Exception e) { 32 | } 33 | return RETURN; 34 | } 35 | 36 | /** 37 | * Send a {@link #VERBOSE} log message and log the exception. 38 | * @param tag Used to identify the source of a log message. It usually identifies 39 | * the class or activity where the log call occurs. 40 | * @param msg The message you would like logged. 41 | * @param tr An exception to log 42 | */ 43 | public static int v(String tag, String msg, Throwable tr) { 44 | try { 45 | if (ISPRINT) 46 | return android.util.Log.v(tag, msg, tr); 47 | } catch (Exception e) { 48 | } 49 | return RETURN; 50 | } 51 | 52 | /** 53 | * Send a {@link #DEBUG} log message. 54 | * @param tag Used to identify the source of a log message. It usually identifies 55 | * the class or activity where the log call occurs. 56 | * @param msg The message you would like logged. 57 | */ 58 | public static int d(String tag, String msg) { 59 | try { 60 | if (ISPRINT) 61 | return android.util.Log.d(tag, msg); 62 | } catch (Exception e) { 63 | } 64 | return RETURN; 65 | } 66 | 67 | /** 68 | * Send a {@link #DEBUG} log message and log the exception. 69 | * @param tag Used to identify the source of a log message. It usually identifies 70 | * the class or activity where the log call occurs. 71 | * @param msg The message you would like logged. 72 | * @param tr An exception to log 73 | */ 74 | public static int d(String tag, String msg, Throwable tr) { 75 | try { 76 | if (ISPRINT) 77 | return android.util.Log.d(tag, msg, tr); 78 | } catch (Exception e) { 79 | } 80 | return RETURN; 81 | } 82 | 83 | /** 84 | * Send an {@link #INFO} log message. 85 | * @param tag Used to identify the source of a log message. It usually identifies 86 | * the class or activity where the log call occurs. 87 | * @param msg The message you would like logged. 88 | */ 89 | public static int i(String tag, String msg) { 90 | try { 91 | if (ISPRINT) 92 | return android.util.Log.i(tag, msg); 93 | } catch (Exception e) { 94 | } 95 | return RETURN; 96 | } 97 | 98 | /** 99 | * Send a {@link #INFO} log message and log the exception. 100 | * @param tag Used to identify the source of a log message. It usually identifies 101 | * the class or activity where the log call occurs. 102 | * @param msg The message you would like logged. 103 | * @param tr An exception to log 104 | */ 105 | public static int i(String tag, String msg, Throwable tr) { 106 | try { 107 | if (ISPRINT) 108 | return android.util.Log.i(tag, msg, tr); 109 | } catch (Exception e) { 110 | } 111 | return RETURN; 112 | } 113 | 114 | /** 115 | * Send a {@link #WARN} log message. 116 | * @param tag Used to identify the source of a log message. It usually identifies 117 | * the class or activity where the log call occurs. 118 | * @param msg The message you would like logged. 119 | */ 120 | public static int w(String tag, String msg) { 121 | try { 122 | if (ISPRINT) 123 | return android.util.Log.w(tag, msg); 124 | } catch (Exception e) { 125 | } 126 | return RETURN; 127 | } 128 | 129 | /** 130 | * Send a {@link #WARN} log message and log the exception. 131 | * @param tag Used to identify the source of a log message. It usually identifies 132 | * the class or activity where the log call occurs. 133 | * @param msg The message you would like logged. 134 | * @param tr An exception to log 135 | */ 136 | public static int w(String tag, String msg, Throwable tr) { 137 | try { 138 | if (ISPRINT) 139 | return android.util.Log.w(tag, msg, tr); 140 | } catch (Exception e) { 141 | } 142 | return RETURN; 143 | } 144 | 145 | /* 146 | * Send a {@link #WARN} log message and log the exception. 147 | * @param tag Used to identify the source of a log message. It usually identifies 148 | * the class or activity where the log call occurs. 149 | * @param tr An exception to log 150 | */ 151 | public static int w(String tag, Throwable tr) { 152 | try { 153 | if (ISPRINT) 154 | return android.util.Log.w(tag, tr); 155 | } catch (Exception e) { 156 | } 157 | return RETURN; 158 | } 159 | 160 | /** 161 | * Send an {@link #ERROR} log message. 162 | * @param tag Used to identify the source of a log message. It usually identifies 163 | * the class or activity where the log call occurs. 164 | * @param msg The message you would like logged. 165 | */ 166 | public static int e(String tag, String msg) { 167 | try { 168 | if (ISPRINT) 169 | return android.util.Log.e(tag, msg); 170 | } catch (Exception e) { 171 | } 172 | return RETURN; 173 | } 174 | 175 | /** 176 | * Send a {@link #ERROR} log message and log the exception. 177 | * @param tag Used to identify the source of a log message. It usually identifies 178 | * the class or activity where the log call occurs. 179 | * @param msg The message you would like logged. 180 | * @param tr An exception to log 181 | */ 182 | public static int e(String tag, String msg, Throwable tr) { 183 | try { 184 | if (ISPRINT) 185 | return android.util.Log.e(tag, msg, tr); 186 | } catch (Exception e) { 187 | } 188 | return RETURN; 189 | } 190 | 191 | /** 192 | * Handy function to get a loggable stack trace from a Throwable 193 | * @param tr An exception to log 194 | */ 195 | public static String getStackTraceString(Throwable tr) { 196 | if (tr == null) { 197 | return ""; 198 | } 199 | StringWriter sw = new StringWriter(); 200 | PrintWriter pw = new PrintWriter(sw); 201 | tr.printStackTrace(pw); 202 | return sw.toString(); 203 | } 204 | } -------------------------------------------------------------------------------- /src/com/vic/http/app/BaseActivity.java: -------------------------------------------------------------------------------- 1 | package com.vic.http.app; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.Locale; 6 | import java.util.Map; 7 | 8 | import android.app.Activity; 9 | import android.app.AlertDialog; 10 | import android.app.AlertDialog.Builder; 11 | import android.app.Dialog; 12 | import android.app.ListFragment; 13 | import android.content.ComponentName; 14 | import android.content.Context; 15 | import android.content.DialogInterface; 16 | import android.content.Intent; 17 | import android.content.res.Configuration; 18 | import android.content.res.Resources; 19 | import android.hardware.Camera.Area; 20 | import android.os.Bundle; 21 | import android.provider.Settings; 22 | import android.util.DisplayMetrics; 23 | import android.view.LayoutInflater; 24 | import android.view.View; 25 | import android.widget.TextView; 26 | 27 | import com.vic.http.common.C; 28 | import com.vic.http.entity.Menu; 29 | import com.vic.http.utils.Network; 30 | //import com.actionbarsherlock.view.Menu; 31 | //import com.actionbarsherlock.view.MenuItem; 32 | 33 | public class BaseActivity extends Activity { 34 | 35 | public Map map; 36 | 37 | public static List activityList = new ArrayList(); 38 | public String tag = this.getClass().getSimpleName(); // tag 用于测试log用 39 | public Context context; // 存储上下文对象 40 | 41 | public static boolean isChangeLangage = true; 42 | 43 | protected ListFragment mFrag; // 标签格式 44 | 45 | @Override 46 | public void onCreate(Bundle savedInstanceState) { 47 | super.onCreate(savedInstanceState); 48 | 49 | // // set the Behind View 50 | // setBehindContentView(R.layout.menu_frame); 51 | // mFrag = (ListFragment)this.getSupportFragmentManager().findFragmentById(R.id.menu_frame); 52 | // 53 | // // customize the SlidingMenu 54 | // SlidingMenu sm = getSlidingMenu(); 55 | // sm.setShadowWidthRes(R.dimen.shadow_width); 56 | // sm.setShadowDrawable(R.drawable.shadow); 57 | // sm.setBehindOffsetRes(R.dimen.slidingmenu_offset); 58 | // sm.setFadeDegree(0.35f); 59 | // sm.setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN); 60 | 61 | // getSupportActionBar().setDisplayHomeAsUpEnabled(true); 62 | if(!(C.display.widthPixels >0 && C.display.heightPixels >0 )){ 63 | DisplayMetrics dm = new DisplayMetrics(); 64 | getWindowManager().getDefaultDisplay().getMetrics(dm); 65 | // 获得手机的宽带和高度像素单位为px 66 | C.display.widthPixels = dm.widthPixels; 67 | C.display.heightPixels = dm.heightPixels; 68 | } 69 | 70 | //初始化 71 | if(activityList == null) activityList = new ArrayList(); 72 | activityList.add(this); 73 | context = this; 74 | 75 | // if(isChangeLangage){ 76 | // Resources resources = getResources();//获得res资源对象 77 | // Configuration config = resources.getConfiguration();//获得设置对象 78 | // DisplayMetrics dm = resources .getDisplayMetrics();//获得屏幕参数:主要是分辨率,像素等。 79 | // String langage = LangageActivity.getStringLangage(context); 80 | // if(langage != null && langage.equals("kr")){ 81 | // config.locale = Locale.KOREAN; // 韩文 82 | // }else{ 83 | // config.locale = Locale.SIMPLIFIED_CHINESE; //简体中文 84 | // } 85 | // resources.updateConfiguration(config, dm); 86 | // isChangeLangage = false; 87 | // } 88 | 89 | //控制切屏模式 90 | // this.setRequestedOrientation(Configuration.ORIENTATION_LANDSCAPE); 91 | this.setRequestedOrientation(Configuration.ORIENTATION_PORTRAIT); 92 | 93 | checkNetWorkShowLog(sendType); 94 | 95 | } 96 | 97 | public void onCreate(Bundle savedInstanceState, boolean isCheckNetwork) { 98 | super.onCreate(savedInstanceState); 99 | if(!(C.display.widthPixels >0 && C.display.heightPixels >0 )){ 100 | DisplayMetrics dm = new DisplayMetrics(); 101 | getWindowManager().getDefaultDisplay().getMetrics(dm); 102 | // 获得手机的宽带和高度像素单位为px 103 | C.display.widthPixels = dm.widthPixels; 104 | C.display.heightPixels = dm.heightPixels; 105 | } 106 | 107 | //初始化 108 | if(activityList == null) activityList = new ArrayList(); 109 | activityList.add(this); 110 | context = this; 111 | 112 | // if(isChangeLangage){ 113 | // Resources resources = getResources();//获得res资源对象 114 | // Configuration config = resources.getConfiguration();//获得设置对象 115 | // DisplayMetrics dm = resources .getDisplayMetrics();//获得屏幕参数:主要是分辨率,像素等。 116 | // String langage = LangageActivity.getStringLangage(context); 117 | // if(langage != null && langage.equals("kr")){ 118 | // config.locale = Locale.KOREAN; // 韩文 119 | // }else{ 120 | // config.locale = Locale.SIMPLIFIED_CHINESE; //简体中文 121 | // } 122 | // resources.updateConfiguration(config, dm); 123 | // isChangeLangage = false; 124 | // } 125 | 126 | //控制切屏模式 127 | // this.setRequestedOrientation(Configuration.ORIENTATION_LANDSCAPE); 128 | this.setRequestedOrientation(Configuration.ORIENTATION_PORTRAIT); 129 | if(isCheckNetwork) 130 | checkNetWorkShowLog(sendType); 131 | } 132 | 133 | // @Override 134 | // public boolean onOptionsItemSelected(MenuItem item) { 135 | // switch (item.getItemId()) { 136 | // case android.R.id.home: 137 | // toggle(); 138 | // return true; 139 | // case R.id.github: 140 | //// Util.goToGitHub(this); 141 | // showSecondaryMenu(); 142 | // return true; 143 | // } 144 | // return super.onOptionsItemSelected(item); 145 | // } 146 | // 147 | // @Override 148 | // public boolean onCreateOptionsMenu(Menu menu) { 149 | // getSupportMenuInflater().inflate(R.menu.main, menu); 150 | // return true; 151 | // } 152 | 153 | @Override 154 | protected void onDestroy() { 155 | super.onDestroy(); 156 | try { 157 | if(activityList != null && activityList.size()>0 && activityList.contains(this)) 158 | activityList.remove(this); 159 | } catch (Exception e) { 160 | e.printStackTrace(); 161 | } 162 | } 163 | 164 | /** 165 | * 退出程序 166 | */ 167 | public static void exit() { 168 | isChangeLangage = true; 169 | for (int i = 0; i < activityList.size(); i++) { 170 | if (null != activityList.get(i)) { 171 | activityList.get(i).finish(); 172 | } 173 | } 174 | activityList = null; 175 | } 176 | 177 | public int sendType = 2; 178 | 179 | @SuppressWarnings("unchecked") 180 | @Override 181 | protected void onRestoreInstanceState(Bundle savedInstanceState) { 182 | super.onRestoreInstanceState(savedInstanceState); 183 | if(savedInstanceState != null){ 184 | 185 | // App.area_name = savedInstanceState.getString("App.area_name"); 186 | // App.area_num = savedInstanceState.getString("App.area_num"); 187 | // App.latitude = savedInstanceState.getDouble("App.latitude", App.latitude); 188 | // App.listAdvs = (ArrayList) savedInstanceState.getSerializable("App.listAdvs"); 189 | // App.listAreas = (ArrayList) savedInstanceState.getSerializable("App.listAreas"); 190 | // App.listMenus = (ArrayList) savedInstanceState.getSerializable("App.listMenus"); 191 | // App.longitude = savedInstanceState.getDouble("App.longitude", App.longitude); 192 | // App.network_name = savedInstanceState.getString("App.network_name"); 193 | // App.nonelatitude = savedInstanceState.getDouble("App.nonelatitude", App.nonelatitude); 194 | // App.nonelongitude = savedInstanceState.getDouble("App.nonelongitude", App.nonelongitude); 195 | // C.display.heightPixels = savedInstanceState.getInt("C.display.heightPixels"); 196 | // C.display.widthPixels = savedInstanceState.getInt("C.display.widthPixels"); 197 | //// App.user = (User) savedInstanceState.getSerializable("App.user"); 198 | //// if(App.user == null) App.user = new User(); 199 | } 200 | } 201 | 202 | @Override 203 | protected void onSaveInstanceState(Bundle outState) { 204 | super.onSaveInstanceState(outState); 205 | // outState.putString("App.area_name", App.area_name); 206 | // outState.putString("App.area_num", App.area_num); 207 | // outState.putDouble("App.latitude", App.latitude); 208 | // outState.putSerializable("App.listAdvs", App.listAdvs); 209 | // outState.putSerializable("App.listAreas", App.listAreas); 210 | // outState.putSerializable("App.listMenus", App.listMenus); 211 | // outState.putDouble("App.longitude", App.longitude); 212 | // outState.putString("App.network_name", App.network_name); 213 | // outState.putDouble("App.nonelatitude", App.nonelatitude); 214 | // outState.putDouble("App.nonelongitude", App.nonelongitude); 215 | // outState.putSerializable("App.user", App.user); 216 | // outState.putInt("C.display.heightPixels", C.display.heightPixels); 217 | // outState.putInt("C.display.widthPixels", C.display.widthPixels); 218 | //// outState.putSerializable("App.mApp", App.mApp); 219 | } 220 | 221 | /** 222 | * 223 | * 检测网络是否正常 224 | * @param type sendType 225 | * @return true:正常 false:不正常 226 | * 创建时间:2012-9-4 下午5:55:03 227 | */ 228 | public boolean checkNetWorkShowLog(final int type){ 229 | //判断网络是否可用 230 | if (!Network.checkNetWork(context)) { // ?行?置?? 231 | Builder b = new AlertDialog.Builder(context).setTitle(R.string.network_show_title) 232 | .setMessage(R.string.network_show_msg); 233 | b.setPositiveButton(R.string.network_show_setting, new DialogInterface.OnClickListener() { 234 | 235 | public void onClick(DialogInterface dialog, int whichButton) { 236 | if(type == 1){ // 设置打开wif 237 | Intent intent=new Intent(Settings.ACTION_WIFI_SETTINGS); 238 | // ComponentName cName = new ComponentName("com.android.phone","com.android.phone.Settings"); 239 | // intent.setComponent(cName); 240 | startActivityForResult(intent,sendType); 241 | sendType = 2; 242 | } else { // 设置打开 3G 243 | Intent intent=new Intent(Settings.ACTION_NETWORK_OPERATOR_SETTINGS); 244 | ComponentName cName = new ComponentName("com.android.phone","com.android.phone.Settings"); 245 | intent.setComponent(cName); 246 | startActivityForResult(intent,sendType); 247 | sendType = 1; 248 | } 249 | } 250 | }).setNeutralButton(R.string.network_show_exit, new DialogInterface.OnClickListener() { 251 | public void onClick(DialogInterface dialog, int whichButton) { 252 | // // 进行跳转 253 | // Message msg = new Message(); 254 | // msg.what = 3; 255 | // mHandler.sendMessage(msg); 256 | // dialog.dismiss(); 257 | BaseActivity.exit(); 258 | } 259 | }).show(); 260 | return false; 261 | } 262 | return true; 263 | } 264 | 265 | @Override 266 | protected void onActivityResult(int requestCode, int resultCode, Intent data) { 267 | checkNetWorkShowLog(sendType); 268 | } 269 | 270 | 271 | @Override 272 | public Dialog onCreateDialog(int id) { 273 | // String show_msg = ""; 274 | int show_title = 0; 275 | LayoutInflater li = (LayoutInflater) getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE); 276 | View dv = (View) li.inflate(R.layout.dialog_progress, null); 277 | switch (id) { 278 | case 1: 279 | // TextView loading = (TextView)dv.findViewById(R.id.loading); 280 | // loading.setText(R.string.progress_loading); 281 | break; 282 | case 2: 283 | // TextView loading2 = (TextView)dv.findViewById(R.id.loading); 284 | // loading2.setText(R.string.progress_login); 285 | break; 286 | case 3: 287 | // TextView loading3 = (TextView)dv.findViewById(R.id.loading); 288 | // loading3.setText(R.string.progress_comment); 289 | break; 290 | case 4: 291 | // show_msg = "获取数据失败"; 292 | show_title = R.string.dialog_title_getDataFail; 293 | break; 294 | case 5: 295 | // show_msg = "网络超时,服务器断开或者请检查网络连接是否正常"; 296 | show_title = R.string.dialog_title_newwork_request_timeout; 297 | break; 298 | case 6: 299 | // show_msg = "暂无数据"; 300 | show_title = R.string.dialog_title_nowData; 301 | break; 302 | case 7: 303 | // show_msg = "获取用户信息失败"; 304 | show_title = R.string.dialog_title_getUserInfoDataFail; 305 | break; 306 | case 8: 307 | // show_msg = "发送数据失败"; 308 | break; 309 | default: 310 | return null; 311 | } 312 | switch (id) { 313 | case 1: 314 | case 2: 315 | case 3: 316 | return new AlertDialog.Builder(this) 317 | .setView(dv).create(); 318 | default: 319 | return new AlertDialog.Builder(this) 320 | .setMessage(show_title) 321 | .setPositiveButton(R.string.confirm, 322 | new DialogInterface.OnClickListener() { 323 | @Override 324 | public void onClick(DialogInterface dialog, 325 | int which) { 326 | dialog.dismiss(); 327 | } 328 | }).create(); 329 | } 330 | } 331 | } 332 | -------------------------------------------------------------------------------- /src/com/vic/http/db/DBHelper.java: -------------------------------------------------------------------------------- 1 | package com.vic.http.db; 2 | 3 | import java.io.BufferedInputStream; 4 | import java.io.ByteArrayInputStream; 5 | import java.io.ByteArrayOutputStream; 6 | import java.io.ObjectInputStream; 7 | import java.io.ObjectOutputStream; 8 | import java.text.SimpleDateFormat; 9 | import java.util.ArrayList; 10 | import java.util.Date; 11 | import java.util.List; 12 | 13 | import android.content.ContentValues; 14 | import android.content.Context; 15 | import android.database.Cursor; 16 | import android.database.sqlite.SQLiteDatabase; 17 | import android.database.sqlite.SQLiteDatabase.CursorFactory; 18 | import android.database.sqlite.SQLiteOpenHelper; 19 | import android.util.Log; 20 | 21 | import com.vic.http.app.R; 22 | import com.vic.http.entity.Store; 23 | import com.vic.utils.Md5Utils; 24 | 25 | /** 26 | * 27 | * 本地数据库 28 | * @author Administrator 29 | * 30 | */ 31 | public class DBHelper extends SQLiteOpenHelper{ 32 | private Context context; 33 | private SQLiteDatabase db; 34 | private static DBHelper mInstance=null; 35 | private static final String DBNAME = "cacheappBigData.db"; 36 | private static final int VERSION = 1; 37 | 38 | // public DBHelper(Context context) { 39 | // this.context = context; 40 | // if(dbHelper == null) 41 | // dbHelper = new SQLiteHelper(this.context); 42 | // } 43 | // private Context context; 44 | 45 | 46 | private DBHelper(Context context, CursorFactory factory) { 47 | // super(context, mDbName, factory, mDbVersion); 48 | super(context, DBNAME, factory, VERSION); 49 | } 50 | 51 | public static DBHelper getInstance(Context context) { 52 | if (mInstance == null) { 53 | mInstance = new DBHelper(context, null); 54 | } 55 | mInstance.context = context; 56 | return mInstance; 57 | } 58 | public static DBHelper getInstance(Context context, 59 | SQLiteDatabase.CursorFactory factory) { 60 | if (mInstance == null) { 61 | mInstance = new DBHelper(context, factory); 62 | } 63 | mInstance.context = context; 64 | return mInstance; 65 | } 66 | 67 | 68 | /** 69 | * 获得url 缓存 70 | * @param url 71 | * @return 72 | */ 73 | public String[] getURLData(String url){ 74 | Cursor cursor = null; 75 | try { 76 | db = getReadableDatabase(); // 获得数据库读对象 77 | cursor = db.rawQuery("select cacheData,createTime from cacheUrlData where url = ?", new String[]{Md5Utils.md5(url)}); 78 | while (cursor.moveToNext()) { 79 | String data =cursor.getString(0); 80 | String time =cursor.getString(1); 81 | cursor.close(); 82 | return new String[]{data,time}; 83 | // return cursor.getString(0); 84 | } 85 | } catch (Exception e) { 86 | e.printStackTrace(); 87 | } finally { 88 | // try { 89 | // if(db != null) 90 | // db.close(); 91 | // } catch (Exception e) { 92 | // e.printStackTrace(); 93 | // } 94 | } 95 | return null; 96 | } 97 | 98 | /** 99 | * 添加或者更新 url 缓存 100 | * @param url 101 | * @param jsonData 102 | */ 103 | public synchronized void addOrUpdateURLData(String url,String jsonData){ 104 | try { 105 | url = Md5Utils.md5(url); 106 | boolean isExists = checkURLData(url); 107 | db = getWritableDatabase(); // 获得数据库写对象 108 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 109 | if(isExists){ 110 | db.execSQL("update cacheUrlData set cacheData =?, createTime = ? where url =? ",new String[]{jsonData, jsonData, sdf.format(new Date()), url}); 111 | }else{ 112 | db.execSQL("insert into cacheUrlData (url, cacheData, createTime) values(?, ?, ?)",new String[]{url, jsonData, sdf.format(new Date())}); 113 | } 114 | } catch (Exception e) { 115 | e.printStackTrace(); 116 | Log.i("db", url); 117 | } finally { 118 | // db.close(); 119 | } 120 | } 121 | 122 | /** 123 | * 删除记录 124 | * @return 125 | */ 126 | public boolean deleteURLData(){ 127 | try{ 128 | db = getWritableDatabase(); // 获得数据库写对象\ 129 | return db.delete("cacheUrlData",null,null) > 0; 130 | }catch(Exception e){ 131 | e.printStackTrace(); 132 | }finally{ 133 | // db.close(); 134 | } 135 | return false; 136 | } 137 | /** 138 | * 删除有记录的url 139 | * @return 140 | */ 141 | public boolean deleteURLData(String url){ 142 | try{ 143 | url = Md5Utils.md5(url); 144 | db = getWritableDatabase(); // 获得数据库写对象\ 145 | return db.delete("cacheUrlData", "url = ?", new String[]{url}) > 0; 146 | }catch(Exception e){ 147 | e.printStackTrace(); 148 | }finally{ 149 | // db.close(); 150 | } 151 | return false; 152 | } 153 | 154 | /** 155 | * 检测是否有url该记录 本类中用 不开放 156 | * @param url 157 | * @return 158 | */ 159 | private synchronized boolean checkURLData(String url){ 160 | Cursor cursor = null; 161 | try { 162 | db = getReadableDatabase(); 163 | cursor = db.rawQuery("select cacheData from cacheUrlData where url = ?", new String[]{url}); 164 | while (cursor.moveToNext()) { 165 | cursor.close(); 166 | return true; 167 | } 168 | } catch (Exception e) { 169 | e.printStackTrace(); 170 | } finally { 171 | // db.close(); 172 | } 173 | return false; 174 | } 175 | 176 | /** 177 | * 添加商店到数据库 暂时缓存 178 | * @param store 179 | * @return 180 | * 创建时间:2012-9-21 下午2:07:03 181 | */ 182 | public boolean addStore(Store store){ 183 | try { 184 | db = getWritableDatabase(); // 获得数据库写对象 185 | // 使用流对象 把对象进行二进制输出 186 | ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); 187 | ObjectOutputStream oos = new ObjectOutputStream(byteStream); 188 | oos.writeObject(store); 189 | // 添加对象到数据库 并记录时间 190 | ContentValues values = new ContentValues(); 191 | values.put("id", store.id); 192 | values.put("blobObj", byteStream.toByteArray()); 193 | oos.close(); 194 | return db.insert("store", "id", values) > 0; 195 | } catch (Exception e) { 196 | e.printStackTrace(); 197 | } finally { 198 | // db.close(); 199 | } 200 | return false; 201 | } 202 | 203 | /** 204 | * 清空商店数据 205 | * @return 206 | */ 207 | public boolean deleteStore(){ 208 | try{ 209 | db = getWritableDatabase(); // 获得数据库写对象\ 210 | return db.delete("store",null,null) > 0; 211 | }catch(Exception e){ 212 | e.printStackTrace(); 213 | }finally{ 214 | // db.close(); 215 | } 216 | return false; 217 | } 218 | 219 | /** 220 | * 获取暂缓商店数据 221 | * @param id 222 | * @return 223 | * 创建时间:2012-9-21 下午2:10:04 224 | */ 225 | public Store getStore(int id){ 226 | String sql = "select id, blobObj from store where id = ?"; 227 | ByteArrayInputStream byteStream = null; // 输入二进制流对象 228 | ObjectInputStream is = null; // 输入数据流化对象 229 | Cursor cursor = null; 230 | try{ 231 | db = getReadableDatabase(); // 获得数据库读对象 232 | cursor = db.rawQuery(sql, new String[]{String.valueOf(id)}); 233 | if (cursor.moveToNext()) { 234 | byte[] tmpByte = cursor.getBlob(cursor.getColumnIndex("blobObj")); 235 | byteStream = new ByteArrayInputStream(tmpByte); // 二进制输入 236 | is = new ObjectInputStream(new BufferedInputStream(byteStream)); // 输入对象 237 | Store store = (Store) is.readObject(); // 进行转化 238 | is.close(); 239 | cursor.close(); 240 | return store; 241 | } 242 | }catch(Exception e){ 243 | e.printStackTrace(); 244 | }finally{ 245 | // cursor.close(); 246 | } 247 | return null; 248 | } 249 | 250 | /** 251 | * 添加收藏到数据库 252 | * @param store 253 | * @return 254 | */ 255 | public boolean addShouCang(Store store){ 256 | SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); 257 | try { 258 | db = getWritableDatabase(); // 获得数据库写对象 259 | // 使用流对象 把对象进行二进制输出 260 | ByteArrayOutputStream byteStream = new ByteArrayOutputStream(); 261 | ObjectOutputStream oos = new ObjectOutputStream(byteStream); 262 | oos.writeObject(store); 263 | // 添加对象到数据库 并记录时间 264 | ContentValues values = new ContentValues(); 265 | values.put("id", store.id); 266 | values.put("blobObj", byteStream.toByteArray()); 267 | values.put("time", sdf.format(System.currentTimeMillis())); 268 | oos.close(); 269 | return db.insert("shoucang", "id", values) > 0; 270 | // db.execSQL("insert into shoucang (id, blobObj, time) values(?, ?, ?)",new Object[]{store.id, byteStream.toByteArray(),sdf.format(System.currentTimeMillis())}); 271 | } catch (Exception e) { 272 | e.printStackTrace(); 273 | } finally { 274 | // db.close(); 275 | } 276 | return false; 277 | } 278 | 279 | /** 280 | * 获取收藏列表 281 | * @return 282 | */ 283 | public List getShouCang(){ 284 | String sql = "select id, blobObj, time from shoucang order by time desc"; 285 | List data = new ArrayList(); 286 | ByteArrayInputStream byteStream = null; // 输入二进制流对象 287 | ObjectInputStream is = null; // 输入数据流化对象 288 | try{ 289 | db = getReadableDatabase(); // 获得数据库读对象 290 | Cursor cursor = db.rawQuery(sql, null); 291 | while (cursor.moveToNext()) { 292 | byte[] tmpByte = cursor.getBlob(cursor.getColumnIndex("blobObj")); 293 | byteStream = new ByteArrayInputStream(tmpByte); // 二进制输入 294 | is = new ObjectInputStream(new BufferedInputStream(byteStream)); // 输入对象 295 | Store store = (Store) is.readObject(); // 进行转化 296 | is.close(); 297 | data.add(store); 298 | } 299 | cursor.close(); 300 | }catch(Exception e){ 301 | e.printStackTrace(); 302 | }finally{ 303 | // db.close(); 304 | } 305 | return data; 306 | } 307 | 308 | /** 309 | * 删除收藏 310 | * @return 311 | */ 312 | public boolean deleteShouCang(String id){ 313 | try{ 314 | db = getWritableDatabase(); // 获得数据库写对象\ 315 | if(id ==null) 316 | return db.delete("shoucang",null,null) > 0; 317 | else 318 | return db.delete("shoucang", "id = ?", new String[]{id}) > 0; 319 | }catch(Exception e){ 320 | e.printStackTrace(); 321 | }finally{ 322 | // db.close(); 323 | } 324 | return false; 325 | } 326 | 327 | /** 328 | * 329 | * 判断是否有收藏记录 330 | * 331 | * @param id 商店id 332 | * @return 333 | */ 334 | public boolean isShouCang(String id){ 335 | String sql = "select time from shoucang where id = ?"; 336 | Cursor cursor=null; 337 | try{ 338 | db = getReadableDatabase(); // 获得数据库读对象 339 | cursor = db.rawQuery(sql, new String[]{id}); 340 | while (cursor.moveToNext()) { 341 | cursor.close(); 342 | return true; 343 | } 344 | }catch(Exception e){ 345 | e.printStackTrace(); 346 | }finally{ 347 | } 348 | return false; 349 | } 350 | 351 | 352 | @Override 353 | public void onCreate(SQLiteDatabase db) { 354 | String [] tables = context.getResources().getStringArray(R.array.sql); 355 | for (int i = 0; i < tables.length; i++) { 356 | db.execSQL(tables[i]); 357 | } 358 | // boolean cof = new DBHelper(context).isColumnExist("emp", "age"); 359 | // String updateSql = "alter table emp add column age text"; 360 | // if(!cof) db.execSQL(updateSql); 361 | } 362 | 363 | @Override 364 | public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { 365 | 366 | } 367 | 368 | /** 369 | * 判断是否有表 370 | * 371 | * @param tableName 372 | * @return 373 | */ 374 | public boolean isTableExist(SQLiteDatabase db, String tableName) { 375 | boolean result = false; 376 | if (tableName == null) { 377 | return false; 378 | } 379 | 380 | try { 381 | Cursor cursor = null; 382 | String sql = "select count(1) as c from sqlite_master where type ='table' and name ='" 383 | + tableName.trim() + "' "; 384 | cursor = db.rawQuery(sql, null); 385 | if (cursor.moveToNext()) { 386 | int count = cursor.getInt(0); 387 | if (count > 0) { 388 | result = true; 389 | } 390 | } 391 | cursor.close(); 392 | } catch (Exception e) { 393 | } 394 | return result; 395 | } 396 | 397 | /** 398 | * 判断是否有字段 399 | * 400 | * @param tableName 401 | * @param columnName 402 | * @return 403 | */ 404 | public boolean isColumnExist(SQLiteDatabase db, String tableName, 405 | String columnName) { 406 | boolean result = false; 407 | if (tableName == null) { 408 | return false; 409 | } 410 | 411 | try { 412 | Cursor cursor = null; 413 | String sql = "select count(1) as c from sqlite_master where type ='table' and name ='" 414 | + tableName.trim() 415 | + "' and sql like '%" 416 | + columnName.trim() + "%'"; 417 | cursor = db.rawQuery(sql, null); 418 | if (cursor.moveToNext()) { 419 | int count = cursor.getInt(0); 420 | if (count > 0) { 421 | result = true; 422 | } 423 | } 424 | cursor.close(); 425 | } catch (Exception e) { 426 | } 427 | return result; 428 | } 429 | } 430 | -------------------------------------------------------------------------------- /src/com/vic/http/http/AnsynHttpRequest.java: -------------------------------------------------------------------------------- 1 | package com.vic.http.http; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.Map; 6 | 7 | import org.apache.http.HttpEntity; 8 | import org.apache.http.HttpResponse; 9 | import org.apache.http.HttpStatus; 10 | import org.apache.http.NameValuePair; 11 | import org.apache.http.client.entity.UrlEncodedFormEntity; 12 | import org.apache.http.client.methods.HttpGet; 13 | import org.apache.http.client.methods.HttpPost; 14 | import org.apache.http.conn.ClientConnectionManager; 15 | import org.apache.http.impl.client.DefaultHttpClient; 16 | import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; 17 | import org.apache.http.message.BasicNameValuePair; 18 | import org.apache.http.params.BasicHttpParams; 19 | import org.apache.http.params.HttpConnectionParams; 20 | import org.apache.http.params.HttpParams; 21 | import org.apache.http.util.EntityUtils; 22 | 23 | import android.app.Activity; 24 | import android.content.Context; 25 | import android.content.Intent; 26 | import android.os.Handler; 27 | import android.os.Message; 28 | 29 | import com.vic.http.app.BaseActivity; 30 | import com.vic.http.app.R; 31 | import com.vic.http.common.C; 32 | import com.vic.http.db.DBHelper; 33 | import com.vic.http.utils.Encoder; 34 | import com.vic.http.utils.Log; 35 | import com.vic.http.utils.Network; 36 | import com.vic.http.utils.ThreadPoolUtils; 37 | import com.vic.http.utils.TimeCompare; 38 | 39 | /** 40 | * 异步数据请求 41 | * @author chen 42 | * @date 2012-10-25 下午2:57:33 43 | */ 44 | public class AnsynHttpRequest { 45 | 46 | public static final int REQUEST_TIMEOUT = 10*1000;//设置请求超时10秒钟 47 | public static final int SO_TIMEOUT = 10*1000; //设置等待数据超时时间10秒钟 48 | static final int POST = 1; // post 提交 49 | static final int GET = 2; // get 提交 50 | 51 | static String tag = AnsynHttpRequest.class.getSimpleName(); 52 | 53 | public static DefaultHttpClient mHttpClient; 54 | /** 55 | * 56 | * 访问网络初始化函数 支持GET请求方式 57 | * 58 | * @param callBack 回调执行函数 支持线程 59 | * @param url 每个执行url 60 | * @param map 参数 61 | * @param isCache 是否本地缓存 62 | * @param isShowDialog 是否弹出提示等待框 63 | */ 64 | public static void requestByGet(Context context, 65 | final ObserverCallBack callBack, int url, Map map, 66 | boolean isCache, boolean isShowDialog) { 67 | //组织URL 68 | StringBuffer buffer = new StringBuffer(); 69 | buffer.append(C.http.http_request_head) 70 | // .append(context.getResources().getString(url)) 71 | .append("?"); 72 | boolean listData = true; 73 | String selectUrl = ""; 74 | if(map != null && map.size()>0){ 75 | String value = ""; 76 | if(map.containsKey("start")){ 77 | if(map.get("start").equals("0")){ 78 | listData = true; 79 | selectUrl = buffer.toString(); 80 | }else 81 | listData = false; 82 | value = "start="+map.get("start")+"&"; 83 | } 84 | for (String key : map.keySet()) { 85 | if(key.equals("start")){ 86 | continue; 87 | } 88 | buffer.append(key) 89 | .append("=") 90 | .append(Encoder.encode(map.get(key))) 91 | .append("&"); 92 | } 93 | buffer.append(value); 94 | } 95 | String requestUrl = buffer.toString(); 96 | requestUrl = requestUrl.substring(0,requestUrl.length()-1); 97 | Log.i("httpurl", requestUrl); 98 | 99 | String[] data = null; 100 | if(isCache){ //如果是缓存 取数据库缓存中数据 101 | data = DBHelper.getInstance(context).getURLData(requestUrl); 102 | } 103 | 104 | switch (Network.checkNetWorkType(context)) { 105 | case /** 网络不可用 */ Network.NONETWORK: 106 | if(data == null ){ 107 | sendBroadcastReceiverMessage(context, R.string.network_show_connectionless); 108 | callBack.back(null, url); 109 | // ((BaseActivity) context).checkNetWorkShowLog(1); 110 | return; 111 | } 112 | break; 113 | case /** 是wifi连接 */ Network.WIFI: 114 | if(data != null && data.length > 0 && listData && TimeCompare.compareHourTime(data[1]) > 3){ 115 | // if(data != null && data.length > 0 && listData && TimeCompare.compareHourTime(data[1]) > 1){ 116 | data = null; 117 | DBHelper.getInstance(context).deleteURLData(selectUrl); 118 | } 119 | break; 120 | case /** 不是wifi连接 */ Network.NOWIFI: // 是 121 | if(data != null && data.length > 0 && listData && TimeCompare.compareHourTime(data[1]) > 24*2){ 122 | // if(data != null && data.length > 0 && listData && TimeCompare.compareHourTime(data[1]) > 1){ 123 | data = null; 124 | DBHelper.getInstance(context).deleteURLData(selectUrl); 125 | } 126 | break; 127 | default: 128 | break; 129 | } 130 | if(isCache && data != null && data.length > 0){ //如果是缓存 取数据库缓存中数据 131 | callBack.back(data[0], url); 132 | return; 133 | } 134 | // 异步请求数据 135 | doAsynRequest(GET, null ,context, callBack, requestUrl, isCache, isShowDialog, url); 136 | } 137 | // /** 138 | // * 139 | // * 访问网络初始化函数 支持GET请求方式 140 | // * 141 | // * @param callBack 回调执行函数 支持线程 142 | // * @param url 每个执行url 143 | // * @param map 参数 144 | // * @param isCache 是否本地缓存 145 | // * @param isShowDialog 是否弹出提示等待框 146 | // */ 147 | // public static void requestByGet(Context context, 148 | // final ObserverCallBack callBack, int url, String requestUrl, 149 | // boolean isCache, boolean isShowDialog) { 150 | // Log.i("httpurl", requestUrl); 151 | // //判断网络是否可用 152 | // if (!Network.checkNetWork(context)) { // 如果不可用 看本地否有数据 153 | // if(isCache){ //如果是缓存 取数据库缓存中数据 154 | // callBack.back(DBHelper.getInstance(context).getURLData(requestUrl), url); 155 | // }else{ 156 | // sendBroadcastReceiverMessage(context, R.string.network_show_connectionless); 157 | // callBack.back(null, url); 158 | // ((BaseActivity) context).checkNetWorkShowLog(1); 159 | // } 160 | // return; 161 | // } 162 | // if(isCache){ //如果是缓存 取数据库缓存中数据 163 | // String cacheData = DBHelper.getInstance(context).getURLData(requestUrl); 164 | // if(cacheData != null){ 165 | // callBack.back(cacheData, url); 166 | // return; 167 | // } 168 | // } 169 | // 170 | // // 异步请求数据 171 | // doAsynRequest(GET, null ,context, callBack, requestUrl, isCache, isShowDialog, url); 172 | // } 173 | 174 | /** 175 | * 异步请求网络数据 176 | * 177 | * @param sendType 请求类型 178 | * @param map 参数 179 | * @param context 180 | * @param callBack 回调对象 181 | * @param url 182 | * @param isCache 是否缓存 183 | * @param isShowDialog 是否有提示框 184 | * @param intUrl 185 | */ 186 | private static void doAsynRequest(final int sendType, 187 | final Map map, final Context context, 188 | final ObserverCallBack callBack, final String url, 189 | final boolean isCache, final boolean isShowDialog, final int intUrl) { 190 | 191 | if(isShowDialog) ((Activity)context).showDialog(1); // 加载对话框提示等待。。 192 | // 请求 193 | ThreadPoolUtils.execute(new MyRunnable(sendType, 194 | map, context, 195 | callBack, url, 196 | isCache, isShowDialog, intUrl)); 197 | } 198 | 199 | /** 200 | * 201 | * 访问网络初始化函数 支持Post请求方式 202 | * 203 | * @param context 204 | * @param callBack 回调执行函数 支持线程 205 | * @param url 每个执行url 206 | * @param map 参数 207 | * @param isCache 是否本地缓存 208 | * @param isShowDialog 是否弹出提示等待框 209 | */ 210 | public static void requestByPost(Context context, 211 | final ObserverCallBack callBack, int url, Map map, 212 | boolean isCache, boolean isShowDialog) { 213 | 214 | //组织URL 215 | StringBuffer buffer = new StringBuffer(); 216 | // buffer.append(C.http.http_request_head); 217 | buffer.append(context.getResources().getString(url)); 218 | 219 | String requestUrl = buffer.toString(); 220 | // requestUrl = requestUrl.substring(0,requestUrl.length()-1); 221 | Log.i("httpurl", requestUrl); 222 | // 异步请求数据 223 | doAsynRequest(POST, map ,context, callBack, requestUrl, isCache, isShowDialog, url); 224 | } 225 | 226 | 227 | /** 228 | * 229 | * 访问网络初始化函数 支持Post请求方式 230 | * 231 | * @param context 232 | * @param http_head 请求头传null或者在C.http类中配置 233 | * @param callBack 回调执行函数 支持线程 234 | * @param url 每个执行url 235 | * @param map 参数 236 | * @param isCache 是否本地缓存 237 | * @param isShowDialog 是否弹出提示等待框 238 | */ 239 | public static void requestByPost(Context context,String http_head, 240 | final ObserverCallBack callBack, int url, Map map, 241 | boolean isCache, boolean isShowDialog) { 242 | 243 | //组织URL 244 | StringBuffer buffer = new StringBuffer(); 245 | if(http_head != null) 246 | buffer.append(http_head); 247 | else 248 | buffer.append(C.http.http_request_head); 249 | 250 | String requestUrl = buffer.toString(); 251 | // requestUrl = requestUrl.substring(0,requestUrl.length()-1); 252 | Log.i("httpurl", requestUrl+map.toString()); 253 | //判断网络是否可用 254 | if (!Network.checkNetWork(context)) { // 如果不可用 看本地否有数据 255 | sendBroadcastReceiverMessage(context, R.string.network_show_connectionless); 256 | callBack.back(null, url); 257 | ((BaseActivity) context).checkNetWorkShowLog(1); 258 | return; 259 | } 260 | // 异步请求数据 261 | doAsynRequest(POST, map ,context, callBack, requestUrl, isCache, isShowDialog, url); 262 | } 263 | 264 | /** 265 | * 通过广播发送网络信息 266 | * @param msg 267 | */ 268 | public static void sendBroadcastReceiverMessage(Context context,int msg){ 269 | // 发送显示消息广播 270 | Intent intent = new Intent("com.fc.apps.vjmenu.app.showmgs"); 271 | intent.putExtra("msg", msg); 272 | context.sendBroadcast(intent); 273 | // BaseActivity.activityList.get(BaseActivity.activityList.size()-1).sendBroadcast(intent); 274 | } 275 | 276 | } 277 | class MyRunnable implements Runnable{ 278 | final int sendType; 279 | final Map map; 280 | final Context context; 281 | final ObserverCallBack callBack; 282 | final String url; 283 | final boolean isCache; 284 | final boolean isShowDialog; 285 | final int intUrl; 286 | 287 | public MyRunnable(final int sendType, 288 | final Map map, final Context context, 289 | final ObserverCallBack callBack, final String url, 290 | final boolean isCache, final boolean isShowDialog, final int intUrl){ 291 | this.sendType = sendType; 292 | this.map = map; 293 | this.context = context; 294 | this.callBack = callBack; 295 | this.url = url; 296 | this.isCache = isCache; 297 | this.isShowDialog = isShowDialog; 298 | this.intUrl = intUrl; 299 | 300 | } 301 | @Override 302 | public void run() { 303 | String data = null; 304 | try { 305 | // SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm0000"); 306 | // String sUserAgent = "code=yyyyMMddHHmmssSS,secretCode=anmaFromAndroid"; 307 | // String time = sdf.format(new Date(System.currentTimeMillis())); 308 | // //加密格式 309 | // StringBuffer sUserAgent = new StringBuffer(); 310 | // sUserAgent 311 | // .append("code=") 312 | // .append(time) 313 | // .append(",secretCode=") 314 | // .append(DESkey.toHexString(DESkey.encryptData(time.getBytes()))); 315 | // Log.i(tag, "mi:"+sUserAgent.toString()); 316 | // 设置请求头超时请求参数 317 | BasicHttpParams httpParams = new BasicHttpParams(); 318 | HttpConnectionParams.setConnectionTimeout(httpParams, AnsynHttpRequest.REQUEST_TIMEOUT); 319 | HttpConnectionParams.setSoTimeout(httpParams, AnsynHttpRequest.SO_TIMEOUT); 320 | if(AnsynHttpRequest.mHttpClient == null){ 321 | // AnsynHttpRequest.mHttpClient = new DefaultHttpClient(httpParams); 322 | DefaultHttpClient client = new DefaultHttpClient(httpParams); 323 | ClientConnectionManager mgr = client.getConnectionManager(); 324 | HttpParams params = client.getParams(); 325 | client = new DefaultHttpClient(new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry()), params); 326 | AnsynHttpRequest.mHttpClient = client; 327 | } 328 | // HttpClient httpClient = HttpUtils.getNewHttpClient(context); 329 | HttpResponse response = null; 330 | switch (sendType) { 331 | case AnsynHttpRequest.GET: // get 方式提交 332 | HttpGet get = new HttpGet(url); 333 | // get.setHeader("User-Agent", sUserAgent.toString()); 334 | response = AnsynHttpRequest.mHttpClient.execute(get); 335 | break; 336 | case AnsynHttpRequest.POST: // post 方式提交 337 | HttpPost post = new HttpPost(url); 338 | // post.setHeader("User-Agent", sUserAgent.toString()); 339 | Log.i("httpurl", url + map.toString()); 340 | List params = new ArrayList(); 341 | if(map != null && map.size()>0) 342 | for (String key : map.keySet()) { 343 | params.add(new BasicNameValuePair(key,map.get(key))); 344 | } 345 | HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8"); 346 | post.setEntity(entity); 347 | response = AnsynHttpRequest.mHttpClient.execute(post); 348 | break; 349 | default: 350 | break; 351 | } 352 | 353 | 354 | if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { 355 | // httpClient.getCookieStore().getCookies().g 356 | data = EntityUtils.toString(response.getEntity()); 357 | if(isCache){// 把数据缓存到本地 358 | DBHelper.getInstance(context).addOrUpdateURLData(url,data); 359 | } 360 | } else { 361 | if(!isCache){ 362 | AnsynHttpRequest.sendBroadcastReceiverMessage(context, R.string.network_show_error); 363 | } 364 | data = null; 365 | } 366 | } catch (Exception e) { 367 | Log.e(AnsynHttpRequest.tag, e.getMessage()); 368 | if(!isCache){ 369 | AnsynHttpRequest.sendBroadcastReceiverMessage(context, R.string.network_show_error); 370 | } 371 | data = null; 372 | } 373 | 374 | try { // 回调数据 375 | if(callBack != null){ 376 | callBack.back(data, intUrl); 377 | if(data !=null) Log.i("httpurl", data); 378 | } 379 | } catch (Exception e) { 380 | Log.e(AnsynHttpRequest.tag, e.getMessage()); 381 | } 382 | try{ 383 | if(isShowDialog) mHandler.sendEmptyMessage(0); // 移除加载对话框 384 | return; 385 | } catch (Exception e) { 386 | Log.e(AnsynHttpRequest.tag, e.getMessage()); 387 | } 388 | } 389 | private Handler mHandler = new Handler(){ 390 | public void handleMessage(Message msg) { 391 | ((Activity)context).removeDialog(1);// 移除加载对话框 392 | }; 393 | }; 394 | } 395 | -------------------------------------------------------------------------------- /src/com/vic/http/http/AnsynHttpRequestV2.java: -------------------------------------------------------------------------------- 1 | package com.vic.http.http; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | import java.util.Map; 6 | 7 | import org.apache.http.HttpEntity; 8 | import org.apache.http.HttpResponse; 9 | import org.apache.http.HttpStatus; 10 | import org.apache.http.NameValuePair; 11 | import org.apache.http.client.entity.UrlEncodedFormEntity; 12 | import org.apache.http.client.methods.HttpGet; 13 | import org.apache.http.client.methods.HttpPost; 14 | import org.apache.http.conn.ClientConnectionManager; 15 | import org.apache.http.impl.client.DefaultHttpClient; 16 | import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager; 17 | import org.apache.http.message.BasicNameValuePair; 18 | import org.apache.http.params.BasicHttpParams; 19 | import org.apache.http.params.HttpConnectionParams; 20 | import org.apache.http.params.HttpParams; 21 | import org.apache.http.util.EntityUtils; 22 | 23 | import android.app.Activity; 24 | import android.content.Context; 25 | import android.content.Intent; 26 | import android.os.Handler; 27 | import android.os.Message; 28 | 29 | import com.vic.http.app.BaseActivity; 30 | import com.vic.http.app.R; 31 | import com.vic.http.common.C; 32 | import com.vic.http.db.DBHelper; 33 | import com.vic.http.utils.Encoder; 34 | import com.vic.http.utils.Log; 35 | import com.vic.http.utils.Network; 36 | import com.vic.http.utils.ThreadPoolUtils; 37 | import com.vic.http.utils.TimeCompare; 38 | 39 | /** 40 | * 异步数据请求 41 | * @author chen 42 | * @date 2012-10-25 下午2:57:33 43 | */ 44 | public class AnsynHttpRequestV2 { 45 | 46 | public static final int REQUEST_TIMEOUT = 10*1000;//设置请求超时10秒钟 47 | public static final int SO_TIMEOUT = 10*1000; //设置等待数据超时时间10秒钟 48 | static final int POST = 1; // post 提交 49 | static final int GET = 2; // get 提交 50 | 51 | static String tag = AnsynHttpRequest.class.getSimpleName(); 52 | 53 | public static DefaultHttpClient mHttpClient; 54 | /** 55 | * 56 | * 访问网络初始化函数 支持GET请求方式 57 | * 58 | * @param callBack 回调执行函数 支持线程 59 | * @param url 每个执行url 60 | * @param map 参数 61 | * @param isCache 是否本地缓存 62 | * @param isShowDialog 是否弹出提示等待框 63 | */ 64 | public static void requestByGet(Context context, 65 | final ObserverCallBack callBack, int url, Map map, 66 | boolean isCache, boolean isShowDialog) { 67 | //组织URL 68 | StringBuffer buffer = new StringBuffer(); 69 | buffer.append(C.http.http_request_head) 70 | // .append(context.getResources().getString(url)) 71 | .append("?"); 72 | boolean listData = true; 73 | String selectUrl = ""; 74 | if(map != null && map.size()>0){ 75 | String value = ""; 76 | if(map.containsKey("start")){ 77 | if(map.get("start").equals("0")){ 78 | listData = true; 79 | selectUrl = buffer.toString(); 80 | }else 81 | listData = false; 82 | value = "start="+map.get("start")+"&"; 83 | } 84 | for (String key : map.keySet()) { 85 | if(key.equals("start")){ 86 | continue; 87 | } 88 | buffer.append(key) 89 | .append("=") 90 | .append(Encoder.encode(map.get(key))) 91 | .append("&"); 92 | } 93 | buffer.append(value); 94 | } 95 | String requestUrl = buffer.toString(); 96 | requestUrl = requestUrl.substring(0,requestUrl.length()-1); 97 | Log.i("httpurl", requestUrl); 98 | 99 | String[] data = null; 100 | if(isCache){ //如果是缓存 取数据库缓存中数据 101 | data = DBHelper.getInstance(context).getURLData(requestUrl); 102 | } 103 | 104 | switch (Network.checkNetWorkType(context)) { 105 | case /** 网络不可用 */ Network.NONETWORK: 106 | if(data == null ){ 107 | sendBroadcastReceiverMessage(context, R.string.network_show_connectionless); 108 | callBack.back(null, url); 109 | // ((BaseActivity) context).checkNetWorkShowLog(1); 110 | return; 111 | } 112 | break; 113 | case /** 是wifi连接 */ Network.WIFI: 114 | if(data != null && data.length > 0 && listData && TimeCompare.compareHourTime(data[1]) > 3){ 115 | // if(data != null && data.length > 0 && listData && TimeCompare.compareHourTime(data[1]) > 1){ 116 | data = null; 117 | DBHelper.getInstance(context).deleteURLData(selectUrl); 118 | } 119 | break; 120 | case /** 不是wifi连接 */ Network.NOWIFI: // 是 121 | if(data != null && data.length > 0 && listData && TimeCompare.compareHourTime(data[1]) > 24*2){ 122 | // if(data != null && data.length > 0 && listData && TimeCompare.compareHourTime(data[1]) > 1){ 123 | data = null; 124 | DBHelper.getInstance(context).deleteURLData(selectUrl); 125 | } 126 | break; 127 | default: 128 | break; 129 | } 130 | if(isCache && data != null && data.length > 0){ //如果是缓存 取数据库缓存中数据 131 | callBack.back(data[0], url); 132 | return; 133 | } 134 | // 异步请求数据 135 | doAsynRequest(GET, null ,context, callBack, requestUrl, isCache, isShowDialog, url); 136 | } 137 | // /** 138 | // * 139 | // * 访问网络初始化函数 支持GET请求方式 140 | // * 141 | // * @param callBack 回调执行函数 支持线程 142 | // * @param url 每个执行url 143 | // * @param map 参数 144 | // * @param isCache 是否本地缓存 145 | // * @param isShowDialog 是否弹出提示等待框 146 | // */ 147 | // public static void requestByGet(Context context, 148 | // final ObserverCallBack callBack, int url, String requestUrl, 149 | // boolean isCache, boolean isShowDialog) { 150 | // Log.i("httpurl", requestUrl); 151 | // //判断网络是否可用 152 | // if (!Network.checkNetWork(context)) { // 如果不可用 看本地否有数据 153 | // if(isCache){ //如果是缓存 取数据库缓存中数据 154 | // callBack.back(DBHelper.getInstance(context).getURLData(requestUrl), url); 155 | // }else{ 156 | // sendBroadcastReceiverMessage(context, R.string.network_show_connectionless); 157 | // callBack.back(null, url); 158 | // ((BaseActivity) context).checkNetWorkShowLog(1); 159 | // } 160 | // return; 161 | // } 162 | // if(isCache){ //如果是缓存 取数据库缓存中数据 163 | // String cacheData = DBHelper.getInstance(context).getURLData(requestUrl); 164 | // if(cacheData != null){ 165 | // callBack.back(cacheData, url); 166 | // return; 167 | // } 168 | // } 169 | // 170 | // // 异步请求数据 171 | // doAsynRequest(GET, null ,context, callBack, requestUrl, isCache, isShowDialog, url); 172 | // } 173 | 174 | /** 175 | * 异步请求网络数据 176 | * 177 | * @param sendType 请求类型 178 | * @param map 参数 179 | * @param context 180 | * @param callBack 回调对象 181 | * @param url 182 | * @param isCache 是否缓存 183 | * @param isShowDialog 是否有提示框 184 | * @param intUrl 185 | */ 186 | private static void doAsynRequest(final int sendType, 187 | final Map map, final Context context, 188 | final ObserverCallBack callBack, final String url, 189 | final boolean isCache, final boolean isShowDialog, final int intUrl) { 190 | 191 | if(isShowDialog) ((Activity)context).showDialog(1); // 加载对话框提示等待。。 192 | // 请求 193 | ThreadPoolUtils.execute(new MyRunnableV2(sendType, 194 | map, context, 195 | callBack, url, 196 | isCache, isShowDialog, intUrl)); 197 | } 198 | 199 | /** 200 | * 201 | * 访问网络初始化函数 支持Post请求方式 202 | * 203 | * @param context 204 | * @param callBack 回调执行函数 支持线程 205 | * @param url 每个执行url 206 | * @param map 参数 207 | * @param isCache 是否本地缓存 208 | * @param isShowDialog 是否弹出提示等待框 209 | */ 210 | public static void requestByPost(Context context, 211 | final ObserverCallBack callBack, int url, Map map, 212 | boolean isCache, boolean isShowDialog) { 213 | 214 | //组织URL 215 | StringBuffer buffer = new StringBuffer(); 216 | // buffer.append(C.http.http_request_head); 217 | buffer.append(context.getResources().getString(url)); 218 | 219 | String requestUrl = buffer.toString(); 220 | // requestUrl = requestUrl.substring(0,requestUrl.length()-1); 221 | Log.i("httpurl", requestUrl); 222 | // 异步请求数据 223 | doAsynRequest(POST, map ,context, callBack, requestUrl, isCache, isShowDialog, url); 224 | } 225 | 226 | 227 | /** 228 | * 229 | * 访问网络初始化函数 支持Post请求方式 230 | * 231 | * @param context 232 | * @param http_head 请求头传null或者在C.http类中配置 233 | * @param callBack 回调执行函数 支持线程 234 | * @param url 每个执行url 235 | * @param map 参数 236 | * @param isCache 是否本地缓存 237 | * @param isShowDialog 是否弹出提示等待框 238 | */ 239 | public static void requestByPost(Context context,String http_head, 240 | final ObserverCallBack callBack, int url, Map map, 241 | boolean isCache, boolean isShowDialog) { 242 | 243 | //组织URL 244 | StringBuffer buffer = new StringBuffer(); 245 | if(http_head != null) 246 | buffer.append(http_head); 247 | else 248 | buffer.append(C.http.http_request_head); 249 | 250 | String requestUrl = buffer.toString(); 251 | // requestUrl = requestUrl.substring(0,requestUrl.length()-1); 252 | Log.i("httpurl", requestUrl+map.toString()); 253 | //判断网络是否可用 254 | if (!Network.checkNetWork(context)) { // 如果不可用 看本地否有数据 255 | sendBroadcastReceiverMessage(context, R.string.network_show_connectionless); 256 | callBack.back(null, url); 257 | ((BaseActivity) context).checkNetWorkShowLog(1); 258 | return; 259 | } 260 | // 异步请求数据 261 | doAsynRequest(POST, map ,context, callBack, requestUrl, isCache, isShowDialog, url); 262 | } 263 | 264 | /** 265 | * 通过广播发送网络信息 266 | * @param msg 267 | */ 268 | public static void sendBroadcastReceiverMessage(Context context,int msg){ 269 | // 发送显示消息广播 270 | Intent intent = new Intent("com.fc.apps.vjmenu.app.showmgs"); 271 | intent.putExtra("msg", msg); 272 | context.sendBroadcast(intent); 273 | // BaseActivity.activityList.get(BaseActivity.activityList.size()-1).sendBroadcast(intent); 274 | } 275 | 276 | } 277 | class MyRunnableV2 implements Runnable{ 278 | final int sendType; 279 | final Map map; 280 | final Context context; 281 | final ObserverCallBack callBack; 282 | final String url; 283 | final boolean isCache; 284 | final boolean isShowDialog; 285 | final int intUrl; 286 | 287 | public MyRunnableV2(final int sendType, 288 | final Map map, final Context context, 289 | final ObserverCallBack callBack, final String url, 290 | final boolean isCache, final boolean isShowDialog, final int intUrl){ 291 | this.sendType = sendType; 292 | this.map = map; 293 | this.context = context; 294 | this.callBack = callBack; 295 | this.url = url; 296 | this.isCache = isCache; 297 | this.isShowDialog = isShowDialog; 298 | this.intUrl = intUrl; 299 | 300 | } 301 | @Override 302 | public void run() { 303 | String data = null; 304 | try { 305 | // SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmm0000"); 306 | // String sUserAgent = "code=yyyyMMddHHmmssSS,secretCode=anmaFromAndroid"; 307 | // String time = sdf.format(new Date(System.currentTimeMillis())); 308 | // //加密格式 309 | // StringBuffer sUserAgent = new StringBuffer(); 310 | // sUserAgent 311 | // .append("code=") 312 | // .append(time) 313 | // .append(",secretCode=") 314 | // .append(DESkey.toHexString(DESkey.encryptData(time.getBytes()))); 315 | // Log.i(tag, "mi:"+sUserAgent.toString()); 316 | // 设置请求头超时请求参数 317 | BasicHttpParams httpParams = new BasicHttpParams(); 318 | HttpConnectionParams.setConnectionTimeout(httpParams, AnsynHttpRequest.REQUEST_TIMEOUT); 319 | HttpConnectionParams.setSoTimeout(httpParams, AnsynHttpRequest.SO_TIMEOUT); 320 | if(AnsynHttpRequest.mHttpClient == null){ 321 | // AnsynHttpRequest.mHttpClient = new DefaultHttpClient(httpParams); 322 | DefaultHttpClient client = new DefaultHttpClient(httpParams); 323 | ClientConnectionManager mgr = client.getConnectionManager(); 324 | HttpParams params = client.getParams(); 325 | client = new DefaultHttpClient(new ThreadSafeClientConnManager(params, mgr.getSchemeRegistry()), params); 326 | AnsynHttpRequest.mHttpClient = client; 327 | } 328 | // HttpClient httpClient = HttpUtils.getNewHttpClient(context); 329 | HttpResponse response = null; 330 | switch (sendType) { 331 | case AnsynHttpRequest.GET: // get 方式提交 332 | HttpGet get = new HttpGet(url); 333 | // get.setHeader("User-Agent", sUserAgent.toString()); 334 | response = AnsynHttpRequest.mHttpClient.execute(get); 335 | break; 336 | case AnsynHttpRequest.POST: // post 方式提交 337 | HttpPost post = new HttpPost(url); 338 | // post.setHeader("User-Agent", sUserAgent.toString()); 339 | Log.i("httpurl", url + map.toString()); 340 | List params = new ArrayList(); 341 | if(map != null && map.size()>0) 342 | for (String key : map.keySet()) { 343 | params.add(new BasicNameValuePair(key,map.get(key))); 344 | } 345 | HttpEntity entity = new UrlEncodedFormEntity(params, "UTF-8"); 346 | post.setEntity(entity); 347 | response = AnsynHttpRequest.mHttpClient.execute(post); 348 | break; 349 | default: 350 | break; 351 | } 352 | 353 | 354 | if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { 355 | // httpClient.getCookieStore().getCookies().g 356 | data = EntityUtils.toString(response.getEntity()); 357 | if(isCache){// 把数据缓存到本地 358 | DBHelper.getInstance(context).addOrUpdateURLData(url,data); 359 | } 360 | } else { 361 | if(!isCache){ 362 | AnsynHttpRequest.sendBroadcastReceiverMessage(context, R.string.network_show_error); 363 | } 364 | data = null; 365 | } 366 | } catch (Exception e) { 367 | Log.e(AnsynHttpRequest.tag, e.getMessage()); 368 | if(!isCache){ 369 | AnsynHttpRequest.sendBroadcastReceiverMessage(context, R.string.network_show_error); 370 | } 371 | data = null; 372 | } 373 | 374 | try { // 回调数据 375 | if(callBack != null) { 376 | final String resData = data; 377 | ((Activity)context).runOnUiThread(new Runnable() { 378 | public void run() { 379 | callBack.back(resData, intUrl); 380 | } 381 | }); 382 | if(data !=null) Log.i("httpurl", data); 383 | } 384 | } catch (Exception e) { 385 | Log.e(AnsynHttpRequest.tag, e.getMessage()); 386 | } 387 | try{ 388 | if(isShowDialog) mHandler.sendEmptyMessage(0); // 移除加载对话框 389 | return; 390 | } catch (Exception e) { 391 | Log.e(AnsynHttpRequest.tag, e.getMessage()); 392 | } 393 | } 394 | private Handler mHandler = new Handler(){ 395 | public void handleMessage(Message msg) { 396 | ((Activity)context).removeDialog(1);// 移除加载对话框 397 | }; 398 | }; 399 | 400 | } 401 | --------------------------------------------------------------------------------