创建一个工具类 HttpUtil
public class HttpUtil {
//定义一个接口
public interface CallBack{
void getData(String s);
}
//封装异步
public static void getHTTP(String url, final CallBack back){
new AsyncTask<String,Void,String>(){
@Override
protected String doInBackground(String... strings) {
return getRequest(strings[0]);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
back.getData(s);
}
}.execute(url);
}
//判断网络状态
public static boolean isNet(Context context){
if(context!=null){
//获取连接管理者
ConnectivityManager manager= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
//获取连接
NetworkInfo isNet = manager.getActiveNetworkInfo();
if(isNet!=null){
return isNet.isAvailable();
}
}
return false;
}
//获取get请求
public static String getRequest(String strUrl){
try {
//将字符串转化成地址
URL url = new URL(strUrl);
//连接地址
HttpURLConnection urlConnection= (HttpURLConnection) url.openConnection();
//设置请求方式
urlConnection.setRequestMethod("GET");
//设置连接超时时间
urlConnection.setConnectTimeout(5000);
//设置读取超时时间
urlConnection.setReadTimeout(5000);
//判断是否请求成功
if(urlConnection.getResponseCode()==200){
InputStream stream = urlConnection.getInputStream();
InputStreamReader in = new InputStreamReader(stream);
BufferedReader reader=new BufferedReader(in);
StringBuffer buffer=new StringBuffer();
String str="";
while ((str=reader.readLine())!=null){
buffer.append(str);
}
return buffer.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
}