android 应用的网络请求工具

       Android应用开发中一般会用到访问网络请求,可以使用socket,webservice等。这里我只是用java中URL,传送数据方式采用json,不考虑数据加密问题。封装的工具类很简单,只提供post,get方法。由于androidUI主线程中不允许启动线程,这里使用FutrueTask启动线程获得返回结果。代码如下:

public class HttpUtil {

    /**
     * get方式访问服务器
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String get(final String url, final Map<String, Object> params)throws Exception{
        String r = null;
        FutureTask<String> task = new FutureTask<String>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                BufferedReader bufferedReader = null;
                String result = null;
                try {
                    String getUrl = url + "?" + getParams(params);
                    Log.i("ApplicationTest", getUrl);
                    URL realUrl = new URL(getUrl);
                    URLConnection connection = realUrl.openConnection();
                    connection.connect();
                    bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String line = null;
                    StringBuffer sb = new StringBuffer();
                    while((line = bufferedReader.readLine())!=null){
                        sb.append(line);
                    }
                    result = sb.toString();
                } catch (IOException e) {
                    Log.i("ApplicationTest", "xxxxx1");
                    e.printStackTrace();
                    throw e;
                }finally {
                    if(bufferedReader != null){
                        try {
                            bufferedReader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                return result;
            }
        });
        new Thread(task).start();

        try {
            r = task.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return r;
    }

    /**
     * post方式访问服务器
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String post(final String url, final Map<String, Object> params)throws Exception{
        String r = null;
        FutureTask<String> task = new FutureTask<String>(new Callable<String>() {
            @Override
            public String call() throws Exception {
                String result = null;
                BufferedReader bufferedReader = null;
                PrintWriter out = null;
                try {
                    String getUrl = url;
                    URL realUrl = new URL(getUrl);
                    URLConnection connection = realUrl.openConnection();
                    connection.setDoOutput(true);
                    connection.setDoInput(true);
                    out = new PrintWriter(connection.getOutputStream());
                    out.print(getParams(params));
                    out.flush();
                    bufferedReader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    String line = null;
                    StringBuffer sb = new StringBuffer();
                    while((line = bufferedReader.readLine())!=null){
                        sb.append(line);
                    }
                    result = sb.toString();
                } catch (IOException e) {
                    e.printStackTrace();
                    throw e;
                }finally {
                    if(bufferedReader != null){
                        try {
                            bufferedReader.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }

                return result;
            }
        });

        new Thread(task).start();
        try {
            r = task.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        return r;
    }

    /**
     * 组装请求参数
     * @param params
     * @return
     */
    private static String getParams(Map<String, Object> params){
        StringBuffer sb = new StringBuffer();
        if(params != null){
            for(String key : params.keySet()){
                sb.append(key).append("=").append(params.get(key).toString()).append("&");
            }
            if(sb.indexOf("&") == sb.length()-1){
                sb.deleteCharAt(sb.length()-1);
            }
        }
        return sb.toString();
    }

}

 如果使用HttpClient工具包,代码会更简单。这里就不列出。



已有 0 人发表留言,猛击->> 这里<<-参与讨论


ITeye推荐
  • —软件人才免语言低担保 赴美带薪读研!—



你可能感兴趣的:(android,网络,应用)