HttpURLConnection, Android访问网络,实用demo

常量

private static final String CHARSET = "UTF-8";
private static final String HTTP_METHOD_POST = "POST";
private static final String PARAMETER_KEY_REN_CODE = "renCode";

1、使用AsyTask访问网络

    class MyAsyncTask extends AsyncTask<String,Void,String> {

        @Override
        protected String doInBackground(String... strings) {
//            http://61.145.196.120:8080/wangbaApp/appUnitRegister?renCode=114419010199
            String url = "http://61.145.196.120:8080/wangbaApp/appUnitRegister";
            Log.i("lgq","ssshhh==onPostExecute====tttt==="+url);
            List<Pair<String, String>> pairs = new ArrayList<Pair<String, String>>();
            pairs.add(new Pair<String, String>(PARAMETER_KEY_REN_CODE, strings[0]));
            String result = doPost(url, pairs);
            return result;
        }

        @Override
        protected void onPostExecute(String ss) {
            super.onPostExecute(ss);
            //隐藏progressBar
            try {
                JSONObject object = new JSONObject(ss);
//                    Log.i("lgq", "re==logtest=====" + s);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }

2、工具方法:

    public static String doPost(String url, List<Pair<String, String>> params) {
        return doRequest(url, params, HTTP_METHOD_POST);
    }

    private static String doRequest(String url, List<Pair<String, String>> params, String type){
//        MLog.d(TAG, "request url : " + url + " method is : " + type);
        InputStream in = null;
        try {

            HttpURLConnection conn = getHttpURLConnection(url);
            conn.setRequestMethod(type);

            if(params != null && !params.isEmpty()){
                setParams(conn, params);
            }

            conn.connect();

//            MLog.d(TAG,"ResponseCode : " + conn.getResponseCode());
            if(HttpURLConnection.HTTP_OK == conn.getResponseCode() ){
                in = conn.getInputStream();
                return readStream(in);
            }else {
                return "网络连接失败"+conn.getURL();
//                throw new NetWorkException("ResponseCode : " + conn.getResponseCode());
            }

        }  catch (IOException e) {
            e.printStackTrace();
//            MLog.w(TAG, e.getMessage(), e);
            return "网络连接失败222";
//            throw new NetWorkException("net work fail: " + e);
        }finally {
            if(in != null){
                try {
                    in.close();
                } catch (IOException e) {
//                    MLog.w(TAG, "io close fail", e);
                }
            }
        }

    }

    private static String readStream(InputStream in) throws IOException {
        char[] buffer = new char[1024];

        BufferedReader reader = new BufferedReader(new InputStreamReader(in, CHARSET));

        int len = 0;
        StringBuilder strBuilder= new StringBuilder();
        while ((len = reader.read(buffer)) != -1){

            strBuilder.append(buffer, 0, len);
        }
        return strBuilder.toString();
    }

    private static HttpURLConnection getHttpURLConnection(String url) throws IOException {
        URL mUrl = new URL(url);

        HttpURLConnection conn = (HttpURLConnection) mUrl.openConnection();
        conn.setReadTimeout(10000);
        conn.setConnectTimeout(15000);

        conn.setDoInput(true);
        conn.setDoOutput(true);

        return conn;
    }

    private static void setParams(HttpURLConnection conn, List<Pair<String, String>> params) throws IOException {

        BufferedWriter writer = null;
        try {

            writer = new BufferedWriter(new OutputStreamWriter(conn.getOutputStream(), CHARSET));

            StringBuilder result = new StringBuilder();
            boolean first = true;
            for (Pair pair : params)
            {
                if (first)
                    first = false;
                else
                    result.append("&");
                result.append(URLEncoder.encode(pair.first.toString(), CHARSET));
                result.append("=");
                result.append(URLEncoder.encode(pair.second.toString(), CHARSET));
            }

//            MLog.d(TAG,"URL:"+result.toString());
            writer.write(result.toString());
            writer.flush();

            Log.i("Lgq","......"+result.toString());

        }finally {
            if(writer != null){
                try {
                    writer.close();
                } catch (IOException e) {
//                    MLog.w(TAG, e.getMessage(), e);
                }
            }
        }


    }

3、开始访问网络

new MyAsyncTask().execute("114419010199");

猜你喜欢

转载自blog.csdn.net/meixi_android/article/details/82628548
今日推荐