安卓中urlconnection的用法

安卓中有时候要与服务器进行网络连接和数据传输,就要用到urlconnection,下面是一个进行网络连接的类

public class NetConection {
    //参数中 String ...content表示可以改变长度的数组,类似stringbuilder和stringbuffer
    public NetConection(final String url, final HttpMethod method,final SuccessCallback successCallback,final FailCallBack failCallBack,final String ...content
    ){
        //网络连接要放在异步线程中
        new AsyncTask, Void, String>() {
            @Override
            protected String doInBackground(Void... params) {
                StringBuffer pram=new StringBuffer();
                for (int i = 0; i <content.length ; i+=2) {
                    pram.append(content[i]).append("=").append(content[i+1]).append("&");

                }
                URLConnection urlConnection;
                try {

                    switch (method){
                        case POST://post方式
                             urlConnection=new URL(url).openConnection();
                            urlConnection.setDoOutput(true);//设置是否向服务器写数据
				//向服务器写数据
                            BufferedWriter bw=new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), Configue.CHARSET));
                            bw.write(pram.toString());
                            bw.flush();//立即发送到服务器
                            break;
                        default://get方式,地址和数据直接在中间用“?”连接在一起
                            urlConnection=new URL(url+"?"+pram.toString()).openConnection();
                            break;
                    }//从服务器读数据
                    BufferedReader br=new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
                    StringBuffer result=new StringBuffer();
                    String line=null;
                    while ((line=br.readLine())!=null){
                        result.append(line);
                    }
                    return result.toString();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(String s) {

                if (s!=null){
                    if (successCallback!=null){
                        successCallback.onSuccess(s);

                    }else {
                        if (failCallBack!=null){
                            failCallBack.onFail();
                        }
                    }
                }
            }
        }.execute();

    }
    //添加两个回调
    public static interface SuccessCallback{
        void onSuccess(String result);
    }
    public static interface FailCallBack{
        void onFail();
    }
}

你可能感兴趣的:(安卓之路)