一个应用程序可能在很多地方要用到网络功能
所以需要把通用的网络操作写到一个公共的类里:
如:
package com.example.networktest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by yuwei on 2016/10/5.
*/
public class HttpUtil {
public static String sendHttpRequest(String address) {
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);
}
return response.toString();
}catch (Exception e){
e.printStackTrace();
return e.getMessage();
}finally {
if(connection!=null){
connection.disconnect();
}
}
}
}
这时调用时:只需要
String address = “http://www.baidu.com”;
String response = HttpUtil.sendHttpRequest(address);
但是一般网络请求都是耗时操作,这样可能导致,主线程被堵塞
直接在sendHttpRequest()内部开启一个子线程是不行的,因为耗时是在子线程中进行,sendHttpRequest()可能在服务器还没响应的时候就已经执行结束了。
所以解决方案是接口的使用
public interface HttpCallbackListener{
void onFinish(String response);
void onError(Exception e);
}
修改原HttpUtil:
package com.example.networktest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by yuwei on 2016/10/5.
*/
public class HttpUtil {
public static String 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);
}
// return response.toString();子线程无法通过return返回数据
if (listener!=null){
listener.onFinish(response.toString());
}
}catch (Exception e){
e.printStackTrace();
if (listener!=null){
listener.onError(e);
}
// return e.getMessage();
}finally {
if(connection!=null){
connection.disconnect();
}
}
}
}).start();
}
public interface HttpCallbackListener{
void onFinish(String response);
void onError(Exception e);
}
}
这时的调用为:
String address = “http://www.baidu.com”;
String response = HttpUtil.sendHttpRequest(address,new HttpCallbackListener(){
public void onFinish(String response){
根据返回的内容执行具体的逻辑
}
public void oNError(Exception e){
对异常情况进行处理
}
});