Android开发之定义接口暴露数据

时间:2023-03-08 17:15:40
Android开发之定义接口暴露数据

写了一个网络请求的工具类,然后想要获取到网络请求的结果,在网络工具类中写了一个接口,暴露除了请求到的数据

代码:

 package com.lijingbo.knowweather.utils;

 import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL; public class HttpUtils {
private static final String TAG = "HttpUtils"; public void getMethod(final String address) {
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(5000);
connection.setReadTimeout(5000);
connection.connect();
if ( connection.getResponseCode() == 200 ) {
InputStream inputStream = connection.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffers = new byte[1024];
int len;
while ( (len = inputStream.read(buffers)) != -1 ) {
baos.write(buffers, 0, len);
}
String result = baos.toString();
httpCallBack.onSuccess(result);
LogUtils.e(TAG, "获取到的服务器信息为:" + result);
baos.close();
inputStream.close(); }
} catch ( IOException e ) {
//网络错误
httpCallBack.onError(e.toString());
e.printStackTrace();
} finally {
if ( connection != null ) {
connection.disconnect();
}
}
}
}).start();
} private HttpCallBack httpCallBack;
public void setHttpListener(HttpCallBack httpCallBack){
this.httpCallBack=httpCallBack;
} public interface HttpCallBack {
void onSuccess(String result);
void onError(String error);
}
}

想要使用该工具类的地方,这样写:

代码:

         HttpUtils httpUtils=new HttpUtils();
httpUtils.getMethod(url);
httpUtils.setHttpListener(new HttpUtils.HttpCallBack() {
@Override
public void onSuccess(String result) {
LogUtils.e(TAG,"网络请求结果:"+result);
} @Override
public void onError(String error) {
LogUtils.e(TAG,"网络请求结果:"+error);
}
});