android之http工具封装类


/**
* http工具类(利用java回掉机制)[注意:还是不能进行UI更新,依然是在子线程中进行的操作]
* 当多次使用http进行网络交互时,可以将其封装在一个类中
* 使用方法:
* 先建一个接口类:如下:
* public interface HttpCallbackListener{
*
* void onFinish(String response)
*
* void onError(Exception e)
*
* }
* 最后在调用类里面利用
* 如下:
*
*
* HttpUtil.sendHttpResquest(address,new HttpCallbackListener(){
* @Override
* public void onFinish(String response){
* //这里对要处理返回数据操作逻辑
*
* }
*
* @Override
* pubic void onError(Exception e){
*
* //这里对异常情况进行处理
*
*}
* })
*
*
* (java这里的回调机制用来解决服务器还没来得及响应时就执行结束的问题。。。。即时间问题,用回调不会去结束方法)
*
*/

 

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(800);
connection.setReadTimeout(8000);
connection.setDoInput(true);
connection.setDoOuput(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){
listener.onError(e);
}finally{
if(connection != null){
connection.disconnect();
}
}
}

}).start();
}
}

posted @ 2015-05-24 22:32  Anumbrella  阅读(813)  评论(0编辑  收藏  举报