HttpPost请求的完美封装

摘要:
/***
 * 封装了post请求的方法:
 * 1.使用了异步AsyncTask + Handler的处理模式;
 * 2.适用于仅仅一条数据的请求,最大的优势在于:能够同时适用于多条数据的请求,并保证数据不出现紊乱;
 * 3.这里面也同时使用了
 *      compile 'com.jakewharton:butterknife:7.0.0'
 *      compile 'com.kaopiz:kprogresshud:1.0.1'
 *  对于这2个三方的类,
 *      虽然kprogresshud有些不足,(kprogresshud--缺点是在进度框显示的过程中不能手动点击取消,只能返回取消)
 *      但是butterknife真是太方便开发了,也有不少人已经介绍了,在此就不多做介绍 (butterknife--引用布局控件非常方便)
 * 4.封装了log打印的类-L.class;
 *      初始化的让其显示log方法 L.isDebug = true;默认不打印log
 * 5.此处的接口都是使用的三方接口:知乎地址:https://www.zhihu.com/question/39479153(未使用)
 *      此处可以将自己的ip接口放上去。
 *
 * 说明:我的qq号:1457521527;欢迎互相学习~
 *  @author yjbo
 *  @create 2016年5月25日18:20:01

*/

已经将源码资源上传到csdn资源包了了,

请下载:http://download.csdn.net/detail/yangjianbo456/9531170

代码摘抄:

一)主类:

public class MainActivity extends AppCompatActivity {

    Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            String msgResult = (String) msg.obj;
            L.i("--handler处理--" + msg.what + "=====" + msgResult);
            switch (msg.what){
                case 1:
                    L.i("--1--"+msgResult);
                    break;

                ......

            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getSupportActionBar().hide();
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
        L.isDebug = true;
        intRequsetData();
        findViewById(R.id.requst_button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                intRequsetData();
            }
        });
    }


    private void intRequsetData() {
        requestData1();
        requestData2();
        requestData3();
        requestData4();
        requestData5();
        requestData3();
    }


    private void requestData1() {
        String methodName0 = Constants.httpIp_aa;
        String[][] stringArr = new String[][]{{"" + 1,methodName0,0+""}
                ,{"json", "ok"}};

        new SimpleAsyRequestUtil(MainActivity.this, R.string.test_pd_running1,mHandler);
        new SimpleAsyRequestUtil.fileUploadTask().execute(stringArr, null, null);
    }
 
 
	......
 
 
}

能实现请求的对话框加载等异步操作:

二)异步处理类

/**
 * 异步处理
 * Created by yjbo on 2016/5/25.
 *
 */
public class SimpleAsyRequestUtil {

    static Activity mactivity;
    private static KProgressHUD hud;
    static int mshowInt =0 ;
    static Handler mhandler;
    public static void scheduleDismiss() {
        if (hud != null) {
            hud.dismiss();
        }
    }
    public SimpleAsyRequestUtil(Activity activity,int showInt,Handler handler) {
        L.i("初始化"+showInt);
        mshowInt = showInt;
        this.mactivity = activity;
        mhandler = handler;
    }

    public static class fileUploadTask extends
            AsyncTask<String[][], String, String[]> {
        @Override
        protected String[] doInBackground(String[][]... params) {
            if (!CommonUtil.checkNet(mactivity)) {//无网络则提示
                return new String[]{Integer.valueOf(params[0][0][0] + "")+"","没有网络"};
            }
          
	Map<String, Object> requestParamsMap0 = new HashMap<String, Object>();
	try {
    		for (int i =0;i < params[0].length-1;i++) {
        	requestParamsMap0.put(params[0][i + 1][0], params[0][i + 1][1]);
    		}
	    }catch (Exception ex){
    		ex.printStackTrace();
	    }
	String[] strResult = new String[]{};
            strResult = SimpleHttpUrlConnUtil.post(mactivity, params[0][0][1] + "", requestParamsMap0,
                        Integer.valueOf(params[0][0][0] + ""));
            return  strResult;
        }

        @Override
        protected void onPreExecute() {
            int showInt = mshowInt;
            String showStr = "";
            if (showInt == 0) {
                showStr = "";
            } else if (showInt == 1){
                showStr =  mactivity.getResources().getString(R.string.pd_running);
            }else{
                showStr = mactivity.getResources().getString(showInt);
            }
            if (!CommonUtil.isNull(showStr)) {
                scheduleDismiss();
                hud = KProgressHUD.create(mactivity)
                        .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE)
                        .setLabel(showStr)
                        .setCancellable(true);
                hud.show();
            }
        }

        @Override
        protected void onProgressUpdate(String... values) {
            super.onProgressUpdate(values);
        }

        @Override
        protected void onPostExecute(String[] result) {

            scheduleDismiss();
            L.i("AsyRequestNewUtil-获取访问的数据" + result[0] + "---" + result[1]);
            Message msg = new Message();
            msg.what = Integer.valueOf(result[0]);
            msg.obj = result[1];
            mhandler.sendMessage(msg);
        }
    }
}
三)http请求
 
/**
 * 数据请求的方法类
 * Created by yjbo on 2016/5/13.
 */
public class SimpleHttpUrlConnUtil {
    public static String[] post(Activity mcontext, String methodName, Map<String, Object> requestParamsMap,
                                int tag) {
        L.i("初始化"+methodName);
        String requestUrl = methodName;//urlCom+
        BufferedReader bufferedReader = null;
        StringBuffer responseResult = new StringBuffer();
        StringBuffer params = new StringBuffer();
        HttpURLConnection httpURLConnection = null;
        Iterator it = requestParamsMap.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry element = (Map.Entry) it.next();
            try {
                params.append(URLEncoder.encode(element.getKey() + "", "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                break;
            }
            params.append("=");
            try {
                params.append(URLEncoder.encode(element.getValue() + "", "UTF-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                break;
            }
            params.append("&");
        }
        if (params.length() > 0) {
            params.deleteCharAt(params.length() - 1);
        }
        try {
            URL realUrl = new URL(requestUrl);
            L.i("HttpUrlConnnewUtil请求的url" + requestUrl + "==" + tag);
            httpURLConnection = (HttpURLConnection) realUrl.openConnection();
            httpURLConnection.setRequestMethod("POST");
            httpURLConnection.setRequestProperty("accept", "*/*");
            httpURLConnection.setRequestProperty("connection", "Keep-Alive");
            httpURLConnection.setRequestProperty("Content-Length", String
                    .valueOf(params.length()));
            httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
            httpURLConnection.setRequestProperty("Charset", "UTF-8");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setConnectTimeout(5000);//设置连接主机超时(单位:毫秒)
            httpURLConnection.setReadTimeout(5000);//设置从主机读取数据超时(单位:毫秒)


            byte[] bypes = params.toString().getBytes();
            httpURLConnection.getOutputStream().write(bypes);
            int responseCode = httpURLConnection.getResponseCode();
            if (responseCode != 200) {
                L.i(mcontext.getResources().getString(R.string.service_back_error) + responseCode + "==" + tag);
            } else {//连接成功
                bufferedReader = new BufferedReader(new InputStreamReader(
                        httpURLConnection.getInputStream()));
                String line;
                while ((line = bufferedReader.readLine()) != null) {
                    responseResult.append("/n").append(line);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
           
	httpURLConnection.disconnect();
   	 try {
        	if (bufferedReader != null) {
           	 bufferedReader.close();
       		 }
    	} catch (IOException ex) {
      		  ex.printStackTrace();
    	}
  	  String result2 = responseResult.toString();
   	 L.i("HttpUrlConnnewUtil运行了finally" + result2 + "==" + tag);
    	if (result2.contains("{") && result2.contains("}")) {
        int indexOfFirst = result2.indexOf("{");
        int indexOfEnd = result2.lastIndexOf("}");
        String strResult1 = "" + result2.substring(indexOfFirst, indexOfEnd + 1);
        if ("10025".equals(CommonUtil.getResult(strResult1, "error"))) {
            Intent mintent = new Intent(mcontext, MainActivity.class);
            mcontext.startActivity(mintent);
        } else {
            return new String[]{tag + "", strResult1};
        }
   	 } else {
       		 L.i("没有取到数据,-----");
       		 return new String[]{tag + "", "没有取到数据"};
    		}

	}
	return new String[]{tag+"","httpConntion请求结束"};
    }
}

二 二

 


 
 

已经将源码资源上传到csdn资源包了了,

请下载:http://download.csdn.net/detail/yangjianbo456/9531170

猜你喜欢

转载自blog.csdn.net/yangjianbo456/article/details/51500887