工具类
package com.qy.day02_asynctask;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class Http {
public static boolean isNetworkConnected(Context context) {
if (context != null) {
//获取连接管理器
ConnectivityManager mConnectivityManager = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
//获取网络状态
NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
if (mNetworkInfo != null) {
//判断网络是否可用
return mNetworkInfo.isAvailable();
}
}
return false;
}
public static String requestHttpGet(String strUrl) {
try { //设置url
URL url = new URL(strUrl);
//获取HttpURLConnection
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//设置为get请求
connection.setRequestMethod("GET");
//设置连接主机超时时间
connection.setConnectTimeout(5000);
//设置从主机读取数据超时
connection.setReadTimeout(5000);
//获取请求码
int code = connection.getResponseCode();
//判断请求是否成功
if (code == HttpURLConnection.HTTP_OK) {
InputStream stream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
//拼接字符串
StringBuffer buffer = new StringBuffer();
String str = "";
while ((str = reader.readLine()) != null) {
buffer.append(str);
}
return buffer.toString();
}
//关闭连接
connection.disconnect();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void httpGET(String url, final CallBackT backT) {
new AsyncTask<String, Void, String>() {
@Override
protected String doInBackground(String... strings) {
//子线程
return requestHttpGet(strings[0]);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
//主线程
backT.getData(s);
}
}.execute(url);
}
public interface CallBackT {
void getData(String s);
}
}
使用方法:
//{ 用法 }
String url="http://api.expoon.com/AppNews/getNewsList/type/1/p/1";
//调用工具类请求数据
Http.httpGET(url, new Http.CallBackT() {
@Override
public void getData(String s) {
//数据就是 s 这个参数
//解析
//设置给控件//例如:text.settext()
}
});