android后台传参的方法

目前我的学习过程中,主要用到以下两个方法向后台传参,代码在更新中,技术不熟练经常懵逼,未免今后读代码时混淆,记录如下

1、AsyncTask

例:在需要和后台友好交流的地方new AsyncQueryTask().execute(Params);

/*AsyncTask:
Params:任务参数类型.
Progress:进度值参数类型(可忽略.
Result:结果的类型.

doInBackground:必写,要完成的任务.
onPreExecute:任务前被调用,我一般用来写提示框.
onPostExecute:线程完成后,自动调用此方法,doInBackground返回的值就是它的传入参数.
*/
    class AsyncQueryTask extends AsyncTask {
        @Override
        protected void onPreExecute() {
            //查询前:可以开启提示框
            //dialog = ProgressDialog.show(mContext, "正在查询", "查询 ...");
        }

        @Override
        protected void onPostExecute(String result) {
            if (dialog.isShowing()) {
                dialog.dismiss();
            }           
            if ("fail".equals(result)) {
                Toast.makeText(getApplication(), "解析失败", Toast.LENGTH_LONG).show();
            } else {
                  
            }
        }

        @Override
        protected FeatureSet doInBackground(String... params) {        
            String response = AllUntils.GetData(url,params);
            return response;
        }
    }

其中AllUntils.GetData(url,params);是新建的AllUntils类下的

public static String GetData(String path,String params) {
        Map map = new HashMap();
        map.put("params", params);      
        try {
            String ret = SocketHttpRequester2.post(path, map, "utf-8");
            return ret;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "fail";
    }

SocketHttpRequester2:

public static String post(String path, Map params, String encode) throws Exception {
        StringBuilder parambuilder = new StringBuilder("");
        if(params!=null && !params.isEmpty()){
            for(Map.Entry entry : params.entrySet()){
                parambuilder.append(entry.getKey()).append("=")
                    .append(URLEncoder.encode(entry.getValue(), encode)).append("&");
            }
            parambuilder.deleteCharAt(parambuilder.length()-1);
        }
        byte[] data = parambuilder.toString().getBytes();
        URL url = new URL(path);
        HttpURLConnection conn = (HttpURLConnection)url.openConnection();
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        conn.setConnectTimeout(5 * 1000);
        conn.setRequestMethod("POST");
        
        conn.setRequestProperty("Accept", "image/gif, image/jpeg, image/pjpeg, image/pjpeg, application/x-shockwave-flash, application/xaml+xml, application/vnd.ms-xpsdocument, application/x-ms-xbap, application/x-ms-application, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
        conn.setRequestProperty("Accept-Language", "zh-CN");
        conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 5.2; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727; .NET CLR 3.0.04506.30; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)");
        conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        conn.setRequestProperty("Content-Length", String.valueOf(data.length));
        conn.setRequestProperty("Connection", "Keep-Alive");

        
        DataOutputStream outStream = new DataOutputStream(conn.getOutputStream());
        outStream.write(data);
        outStream.flush();
        outStream.close();
        if(conn.getResponseCode()==200){
            String str = new String(readStream(conn.getInputStream()));
            return str;
        }
        return "fail";
    }

以上是异步的写法,比较繁琐
下面用的是Afinal的框架,比较简单

2、finalHttp.post(url, ajaxparams, callBack);

Afinal四大模块:FinalDB、FinalActivity、FinalHttp、FinalBitmap,都很好用!!非常好用!!!(加jar、加权限)
然后!和后台的友好交流!只需要一句话!代替上面一大堆!

public FinalHttp finalHttp;
finalHttp.post(url, ajaxparams, callBack);

其中ajaxparams就是你的上传参数,如:

AjaxParams ajaxparams = new AjaxParams();
ajaxparams.put("name", "张三");

callBack就是返回的数据啦!

AjaxCallBack callback = new AjaxCallBack() {
        @Override
        public void onSuccess(String t) {
            // TODO Auto-generated method stub
            super.onSuccess(t);
        }
        @Override
        public void onFailure(Throwable t, int errorNo, String strMsg) {          
            super.onFailure(t, errorNo, strMsg);
          }
    };

你可能感兴趣的:(android后台传参的方法)