异步请求工具类NetTool

来源:互联网 发布:车牌选号软件 编辑:程序博客网 时间:2024/06/12 22:58

public class NetTool {
    private String url = "";
    private String method = "";
    private String body = "";
    
    public NetTool() {
        super();
    }
    /**
     * 发起网络请求
     *
     * @param httpData
     * @param listener
     */
    public static MAsyncTask loadData(final HttpData httpData,
            final HttpListener listener) {

        if (null == listener) {
            return null;
        }
        MAsyncTask task=new MAsyncTask(listener);
        task.execute(httpData);
        return task;
    }
    
    public static class MAsyncTask extends AsyncTask<HttpData, Integer, String> {

        HttpListener listener;
        public MAsyncTask(HttpListener listener){
            this.listener=listener;
        }      

        @Override
        protected String doInBackground(HttpData... params) {
            String result="";
            if(isCancelled()){
                return null;
            }
            if(params!=null){
                result=httpClientPost(params[0]);
                if(!TextUtils.isEmpty(result)){
                    result=Aes.aesDncrypt(result);
                }
            }
            return  result;
        }
        @Override
        protected void onProgressUpdate(Integer... values) {
            //Log.e("函数调用", "onProgressUpdate");
            //if(isCancelled()) {Log.e("Task停止运行", "Task停止运行");return;}
        }
        
        @Override
        protected void onPostExecute(String result) {
            HttpResult resultObj = null;
            ResultStatus status = null;
            if(result!=null&& result.length()>0){
                status = ResultStatus.HTTP_OK;
            }else{
                status = ResultStatus.HTTP_ERR;
            }
            resultObj = new HttpResult(status, result);
             listener.onResult(resultObj);
        }

    }
    
    /**
     * 以post方式发送请求,访问web
     *
     * @param uri
     *            web地址
     * @return 响应数据
     */
    private static  String httpClientPost(HttpData httpData) {
        String result=null;
        HttpParams httpParams = new BasicHttpParams();
        //httpParams.setParameter("marktype", httpData.getBody());
        int timeOut=50000,newTimeOut=0;
        newTimeOut=MApplication.getInt(Constants.HTTP_CONNECT_TIMEOUT, 0);
        if(0!=newTimeOut){
            timeOut=newTimeOut;
            MApplication.remove(Constants.HTTP_CONNECT_TIMEOUT);
        }
        HttpConnectionParams.setConnectionTimeout(httpParams,
                timeOut);
        HttpConnectionParams.setSoTimeout(httpParams,timeOut);

        HttpClient client = new DefaultHttpClient(httpParams);
        
        HttpPost request = new HttpPost(httpData.getUrl());
        Log.e("网络数据请求地址", httpData.getUrl());
        Log.e("网络数据请求参数", httpData.getBody());
        // 保存要传递的参数
        //List<NameValuePair> params = new ArrayList<NameValuePair>();
        // 添加参数
        //params.add(new BasicNameValuePair("marktype", httpData.getBody()));

        // 创建UrlEncodedFormEntity对象  
       
        
        
        try {
            // 设置字符集
            //HttpEntity entity = new UrlEncodedFormEntity(params, "utf-8");
            // 请求对象
            StringEntity entity=new StringEntity(Aes.aesEncrypt(httpData.getBody()),"utf-8");
            entity.setContentEncoding("UTF-8");    
            entity.setContentType("application/json");   
            request.setEntity(entity);
            // 发送请求
            HttpResponse response = client.execute(request);
            // 请求成功
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result=EntityUtils.toString(response.getEntity(),HTTP.UTF_8);
            }
        } catch (ClientProtocolException e) {
            if(Constants.LOG_PRINT){
                e.printStackTrace();
            }
        } catch (IOException e) {
            if(Constants.LOG_PRINT){
                e.printStackTrace();
            }
        }
        return result;
    }
  //版本升级的请求 
    private static void getVersionInfo(final Context context,final VersionCallback callback){
        try {
            HttpData data=new HttpData(Constants.NEW_VERSION_CHECK,  new JSONObject("{\"os\":\"android\"}").toString());
            NetTool.loadData(data, new HttpListener() {
                
                @Override
                public void onResult(HttpResult result) {
                    if(result.getHttpStatus()==ResultStatus.HTTP_OK){
                        String resultStr=result.getResult();
                        Log.i("tag", "联网返回的版本信息=="+resultStr);
                        VersionInfo versionInfo=new Gson().fromJson(resultStr, VersionInfo.class);
                        int versionCode=0;
                        try {
                            versionCode = context.getPackageManager().getPackageInfo(context.getPackageName(),0).versionCode;
                            Log.i("tag", "之前版本号:versionCode=="+versionCode);
                        } catch (NameNotFoundException e) {
                            e.printStackTrace();
                        }
                        int netVersionCode = versionInfo.getVersion_code();
                        Log.i("tag", "联网获取的最新版本号:netVersionCode=="+netVersionCode);
                        if(versionInfo!=null&&versionCode!=0&&netVersionCode>versionCode){
                            callback.isNewVersion(versionInfo);
                        }else{
                            callback.isNewVersion(null);
                        }
                    }
                }
            });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    public static void versionCheck(Context context,VersionCallback callback){
        NetTool.getVersionInfo(context,callback);
    }
    public static void downNewVersion(Context context,VersionInfo info){
        if(!TextUtils.isEmpty(info.getDownloadUrl())){
            FileDownLoad downLoad=new FileDownLoad(context,info.getDownloadUrl(),"apk");
            downLoad.enqueue(context,context.getResources().getString(R.string.app_name),context.getResources().getString(R.string.app_name)+"下载更新");
        }
    }
    public static void downExcel(Context context,String path,String type){
        if(!TextUtils.isEmpty(path)){
            FileDownLoad downLoad=new FileDownLoad(context,path,"xls");
            downLoad.enqueue(context,context.getResources().getString(R.string.app_name),context.getResources().getString(R.string.app_name)+"xxx下载");
        }
    }
    
    
    
    
    public interface VersionCallback{
        public void isNewVersion(VersionInfo info);
    }
    /**
     * @return the url
     */
    public String getUrl() {
        return url;
    }

    /**
     * @param url
     *            the url to set
     */
    public void setUrl(String url) {
        this.url = url;
    }

    /**
     * @return the method
     */
    public String getMethod() {
        return method;
    }

    /**
     * @param method
     *            the method to set
     */
    public void setMethod(String method) {
        this.method = method;
    }

    /**
     * @return the body
     */
    public String getBody() {
        return body;
    }

    /**
     * @param body
     *            the body to set
     */
    public void setBody(String body) {
        this.body = body;
    }

}

public class HttpData {
    
    private String url = "";
    private int timeout = 0;
    private String body = "";
    
    /**
     * @param url
     * @param body
     */
    public HttpData(String url, String body) {
        super();
        this.url = url;
        this.body = body;
        this.timeout = 10000;
    }

    /**
     * @param url
     * @param timeout
     * @param body
     */
    public HttpData(String url, int timeout, String body) {
        super();
        this.url = url;
        this.timeout = timeout;
        this.body = body;
    }

    /**
     *
     */
    public HttpData() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @return the url
     */
    public String getUrl() {
        return url;
    }
    /**
     * @param url the url to set
     */
    public void setUrl(String url) {
        this.url = url;
    }
    /**
     * @return the timeout
     */
    public int getTimeout() {
        return timeout;
    }
    /**
     * @param timeout the timeout to set
     */
    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }
    /**
     * @return the body
     */
    public String getBody() {
        return body;
    }
    /**
     * @param body the body to set
     */
    public void setBody(String body) {
        this.body = body;
    }
}

public interface HttpListener {

    public void onResult(HttpResult result);
}

 

public enum ResultStatus {

    HTTP_OK,
    HTTP_ERR
}

 

 

0 0
原创粉丝点击