1. 封装HttpURLConnection的网络请求
///定义一个接口
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) {
//接收到服务器返回的数据,回调onFinish方法,将数据传出去
listener.onFinish(response.toString());
}
} catch (Exception e) {
e.printStackTrace();
//请求出错,回调onError()方法
listener.onError(e);
} finally {
if (connection != null) {
connection.disconnect();
}
}
}
}).start();
}
}
String address = "http://10.0.2.2/get_data.json";
HttpUtil.sendHttpRequest(address, new HttpCallbackListener() {
@Override
public void onFinish(String response) {
//解析服务器返回的数据
parseJSONWithGSON(response);
}
@Override
public void onError(Exception e) {
//请求失败做的操作
}
});
2. 封装OKHttp的网络请求
///封装OKHttp的网络请求
public static void sendOkHttpRequest(String address, okhttp3.Callback callback) {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(address)
.build();
client.newCall(request).enqueue(callback);
}
String address = "http://10.0.2.2/get_data.json";
HttpUtil.sendOkHttpRequest(address, new Callback() {
@Override
public void onFailure(Call call, IOException e) {
//请求失败时调用
}
@Override
public void onResponse(Call call, Response response) throws IOException {
//收到服务器返回的数据调用
//收到服务器返回的数据调用
String responseData = response.body().string();
showRespons(responseData);
}
});