package com.bwei.net;
import android.os.AsyncTask;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
public class UtilsNet {
private static final UtilsNet ourInstance = new UtilsNet();
public static UtilsNet getInstance() {
return ourInstance;
}
private UtilsNet() {
}
//1.请求网址的方法
public void getUrl(String url){
new getData().execute(url);
}
//2.获取流文件
class getData extends AsyncTask<String,Integer,String>{
@Override
protected String doInBackground(String... strings) {
try {
URL url = new URL(strings[0]);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setConnectTimeout(5000);
connection.setReadTimeout(5000);
connection.setRequestMethod("GET");
if (connection.getResponseCode()==200){
return String2Stream(connection.getInputStream());
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
//5.判断
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
if (s == null ){
netCallBack.onError("错误");
}else {
netCallBack.onSeccess(s);
}
}
}
//3.把字符文件转换成流文件
private String String2Stream(InputStream inputStream) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] bytes = new byte[1024];
int len = 0;
try {
while ((len = inputStream.read(bytes))!=-1){
bos.write(bytes,0,len);
}
} catch (Exception e) {
e.printStackTrace();
}
return new String(bos.toByteArray());
}
//4.创建方法
private NetCallBack netCallBack;
//4.1
public void setNetCallBack(NetCallBack netCallBack){
this.netCallBack = netCallBack;
}
//4.2
public interface NetCallBack{
void onSeccess(String s);
void onError(String e);
}
//1.异步加载轮播
public void loadInage(final String url,final NetCallBack netCallBack){
new Thread(){
@Override
public void run() {
super.run();
try {
URL url1 = new URL(url);
HttpURLConnection connection = (HttpURLConnection) url1.openConnection();
connection.setReadTimeout(5000);
connection.setConnectTimeout(5000);
connection.setRequestMethod("GET");
if (connection.getResponseCode()==200){
netCallBack.onSeccess(String2Stream(connection.getInputStream()));
}
} catch (Exception e) {
e.printStackTrace();
}
}
}.start();
}
}