码迷,mamicode.com
首页 > 移动开发 > 详细

android笔记20170116

时间:2017-01-16 22:38:34      阅读:336      评论:0      收藏:0      [点我收藏+]

标签:listen   exception   get   ati   runnable   res   ror   span   方法   

封装http请求类,利用回调机制获取返回值

public interface HttpCallbackListener {

    void onFinish(String response);
    
    void onError(Exception e);
}
public class HttpUtil {
    public static void sendHttpRequest(final String address, final HttpCallbackListener listener){
        new Thread(new Runnable(){

            @Override
            public void run() {
                HttpURLConnection connection = null;
                
                try {
                    URL url = new URL(address);
                    connection = (HttpURLConnection) url.openConnection();
                    connection.setRequestMethod("GET");
                    connection.setConnectTimeout(8000);
                    connection.setReadTimeout(8000);
                    connection.setDoInput(true);
                    connection.setDoOutput(true);
                    InputStream in = connection.getInputStream();
                    BufferedReader reader = new BufferedReader(new InputStreamReader(in));
                    StringBuilder response = new StringBuilder();
                    String line;
                    while((line = reader.readLine()) != null){
                        response.append(line);
                    }
                    if(listener != null){
                        listener.onFinish(response.toString());
                    }
                } catch (Exception e) {
                    if(listener != null){
                        listener.onError(e);
                    }
                } finally{
                    if(connection != null){
                        connection.disconnect();
                    }
                }
            }
            
        }).start();
    }
}

使用方法:

HttpUtil.sendHttpRequest("address", new HttpCallbackListener() {
            
            @Override
            public void onFinish(String response) {
                
            }
            
            @Override
            public void onError(Exception e) {
                
            }
        });

需要注意的是,最终的回调接口还是在子线程中运行的,因此我们不可以在这里执行任何的UI操作,除非借助runOnUiThread()方法来进行线程转换

android笔记20170116

标签:listen   exception   get   ati   runnable   res   ror   span   方法   

原文地址:http://www.cnblogs.com/919czzl/p/6291152.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!