HttpUtils工具类

public class HttpUtils {
public static void httpAsynTask(String strUrl, final CallBackString backString){
new AsyncTask(){
@Override
protected String doInBackground(String… strings) {
return httpGet(strings[0]);
}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    //接口回调的方法
    backString.getData(s);
}

}.execute(strUrl);

}
//接口
public interface CallBackString{
void getData(String s);
}
public static String httpGet(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);
//得到数据
InputStream stream=connection.getInputStream();
BufferedReader reader=new BufferedReader(new InputStreamReader(stream));
//拼接数据
StringBuilder builder=new StringBuilder();
String str="";
while ((str=reader.readLine())!=null){
builder.append(str);
}
//关闭连接
connection.disconnect();
//返回数据
return builder.toString();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}

你可能感兴趣的:(HttpUtils工具类)