1) 先定义一个接口
public interface HttpCallbackListener {
void onFinish(String response);
void onError(Exception e);
}
2) 在工具类HttpUtil中定义一个静态方法sendHttpReq()
static void sendHttpReq(final String address, final HttpCallbackListener listener){
new Thread(new Runnable() {
@Override
public void run() {
HttpURLConnection connection = null;
StringBuilder builder = null;
try {
URL url = new URL(address);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.connect();//要在清单文件中声明连接网络的权限
if (200 == connection.getResponseCode()){
Log.e("lyl", "连接成功");
InputStream is = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line = null;
builder = new StringBuilder();
while ((line = reader.readLine()) != null){
builder.append(line);
}
}
Log.e("lyl", "builder : " + builder.toString());
if ((null != builder.toString()) && (null != listener)){
listener.onFinish(builder.toString());
}
} catch (Exception e) {
e.printStackTrace();
if (null != listener){
listener.onError(e);
}
} finally {
if (null != connection){
connection.disconnect();
connection = null;
}
}
}
}).start();
开启子线程发起http请求,服务器响应的数据传入HttpCallbackListener的onFinish()方法
3) 传入url,在UI线程中更新出来得到的数据
HttpUtil.sendHttpReq("https://www.baidu.com/", new HttpCallbackListener() {
@Override
public void onFinish(final String res) {
Log.e("lyl", "onFinish: " + res);
//要开启UI线程进行view更新,否则会报错:
//Only the original thread that created a view hierarchy can touch its views.
runOnUiThread(new Runnable() {
@Override
public void run() {
tv_text.setText(res);
}
});
}
@Override
public void onError(Exception e) {
}
});
4) 使用Okhttp:
//在build.gradle中添加依赖 compile 'com.squareup.okhttp3:okhttp:3.7.0'
static void sendOkHttpReq(String add, okhttp3.Callback callback){
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(add)
.build();
client.newCall(request).enqueue(callback);
}
HttpUtil.sendOkHttpReq("https://www.baidu.com/", new okhttp3.Callback() {
@Override
public void onResponse(Call call, final Response response) throws IOException {
runOnUiThread(new Runnable() {
@Override
public void run() {
tv_text.setText(response.toString());
}
});
}
@Override
public void onFailure(Call call, IOException e) {
}
});
在okhttp3.Callback接口中定义了
void onFailure(Call call, IOException e);
void onResponse(Call call, Response response) throws IOException;