开发代码中调用:
HttpUtils.send(HttpUtils.METHOD_POST, path, new RquestCallBack() {
@Override
public void onSuccess(String info) {
//网络请求成功后
}
@Override
public void onFail(Exception e, String info) {
//网络请求异常
}
});
网络工具类:HttpUtils.java
作用:HttpUtils在使用requestCallBack时并不考虑,onSuccess、onFail方法的具体实现。这两个方法是代码编写者调用HttpUtils.send时,实现的
public class HttpUtils {
public static final String METHOD_POST = "POST";
public static final String METHOD_GET = "GET";
private static InputStream is;
public static void send(final String method, final String url, final RquestCallBack rquestCallBack) {
new Thread() {
@Override
public void run() {
try {
//1.为空判断
if (!TextUtils.isEmpty(url)) {
//1、创建一个浏览器
HttpClient client = new DefaultHttpClient();
//2、输入一个网址
HttpGet httpGet = new HttpGet(url);
//3、按回车
HttpResponse response = client.execute(httpGet);
//4、获取服务器端返回的响应数据,判断响应码,200ok,404找不到资源、503服务器内部错误
int code = response.getStatusLine().getStatusCode();
System.out.println(code);
if (200 == code) {
is = response.getEntity().getContent();
rquestCallBack.onSuccess(StreamUtils.converStream2String(is));
} else {
rquestCallBack.onFail(null, "请求错误码:" + code);
}
}
} catch (ClientProtocolException e) {
rquestCallBack.onFail(e, "请求网络异常");
e.printStackTrace();
} catch (IOException e) {
rquestCallBack.onFail(e, "请求网络异常");
e.printStackTrace();
}
}
}.start();
}
}
回调接口类:RquestCallBack
public interface RquestCallBack {
public void onSuccess(String info);
public void onFail(Exception exception, String info);
}