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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章