Android开发之定义接口暴露数据
写了一个网络请求的工具类,然后想要获取到网络请求的结果,在网络工具类中写了一个接口,暴露除了请求到的数据
代码:
1 package com.lijingbo.knowweather.utils; 2 3 import java.io.ByteArrayOutputStream; 4 import java.io.IOException; 5 import java.io.InputStream; 6 import java.net.HttpURLConnection; 7 import java.net.URL; 8 9 10 public class HttpUtils { 11 private static final String TAG = "HttpUtils"; 12 13 public void getMethod(final String address) { 14 new Thread(new Runnable() { 15 @Override 16 public void run() { 17 HttpURLConnection connection = null; 18 try { 19 URL url = new URL(address); 20 connection = (HttpURLConnection) url.openConnection(); 21 connection.setRequestMethod("GET"); 22 connection.setConnectTimeout(5000); 23 connection.setReadTimeout(5000); 24 connection.connect(); 25 if ( connection.getResponseCode() == 200 ) { 26 InputStream inputStream = connection.getInputStream(); 27 ByteArrayOutputStream baos = new ByteArrayOutputStream(); 28 byte[] buffers = new byte[1024]; 29 int len; 30 while ( (len = inputStream.read(buffers)) != -1 ) { 31 baos.write(buffers, 0, len); 32 } 33 String result = baos.toString(); 34 httpCallBack.onSuccess(result); 35 LogUtils.e(TAG, "获取到的服务器信息为:" + result); 36 baos.close(); 37 inputStream.close(); 38 39 } 40 } catch ( IOException e ) { 41 //网络错误 42 httpCallBack.onError(e.toString()); 43 e.printStackTrace(); 44 } finally { 45 if ( connection != null ) { 46 connection.disconnect(); 47 } 48 } 49 } 50 }).start(); 51 } 52 53 private HttpCallBack httpCallBack; 54 public void setHttpListener(HttpCallBack httpCallBack){ 55 this.httpCallBack=httpCallBack; 56 } 57 58 public interface HttpCallBack { 59 void onSuccess(String result); 60 void onError(String error); 61 } 62 }
想要使用该工具类的地方,这样写:
代码:
1 HttpUtils httpUtils=new HttpUtils(); 2 httpUtils.getMethod(url); 3 httpUtils.setHttpListener(new HttpUtils.HttpCallBack() { 4 @Override 5 public void onSuccess(String result) { 6 LogUtils.e(TAG,"网络请求结果:"+result); 7 } 8 9 @Override 10 public void onError(String error) { 11 LogUtils.e(TAG,"网络请求结果:"+error); 12 } 13 });
直面挑战,躬身入局