android解析网络json数据(1)

1.首先获得url,传入URL类,利用URL的openconnection方法,获得URLConnection,去的输入流,进行操作,具体代码如下:

public class NetConnection{
    public NetConnection(final String url,final HttpMethod method,final SuccessCallback successCallback,
            final FailCallback failCallback,final String ... key){
        new AsyncTask<Void, Void, String>() {

            protected String doInBackground(Void... params) {
                StringBuffer parameter = new StringBuffer();
                for (int i = 0; i < key.length; i+=2) {
                    parameter.append(key[i]).append("=").append(key[i+1]).append("&");
                }
                try {
                    URLConnection uc = null;
                    switch(method){
                    case POST:
                        uc = new URL(url).openConnection();
                        uc.setDoInput(true);
                        uc.setDoOutput(true);
                        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(uc.getOutputStream(),
                                Config.CHARSET));
                        bw.write(parameter.toString());
                        bw.flush();
                        break;
                    default:
                        uc = new URL(url+"?"+parameter.toString()).openConnection();
                        break;
                    }
                    System.out.println("request url:"+uc.getURL());
                    System.out.println("request data:"+parameter);
                    BufferedReader bf = new BufferedReader(new InputStreamReader(uc.getInputStream(), Config.CHARSET));
                    String line = null;
                    StringBuffer sb = new StringBuffer();
                    while ((line = bf.readLine()) != null) {
                        sb.append(line);
                    }
                    System.out.println("result:"+sb);
                    return sb.toString();
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }
            @Override
            protected void onPostExecute(String result) {
                if (result != null) {
                    if (successCallback != null) {
                        successCallback.onSuccess(result);
                    }
                }else {
                    if (failCallback != null) {
                        failCallback.onFail();
                    }
                }
                super.onPostExecute(result);
            }
        }.execute();
    }
    public static interface SuccessCallback{
        void onSuccess(String result);
    }
    public static interface FailCallback{
        void onFail();
    }
}

里面封装了两个接口,SuccessCallback和FailCallback,分别用于实现这个类的时候重写,来执行取得数据和灭幼取得数据的情况。参数中用字符串包含了请求参数。

上一篇:处理日期时间NSDate


下一篇:JavaScript闭包示例