public class NetUtil {
private static List<ContentBean.Data> data;
//获取网络的连接
public static List<ContentBean.Data> getRequest(String path){
try {
HttpURLConnection urlConnection = (HttpURLConnection) new URL(path).openConnection();
int responseCode = urlConnection.getResponseCode();
if(responseCode == 200){
//调用转换字符串的方法
String result = getstring(urlConnection.getInputStream());
ContentBean bean = new Gson().fromJson(result, ContentBean.class);
data = bean.getData();
return data;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static void getBitmap(final String imageUrl, final Callback callback){
new AsyncTask<String, Void, Bitmap>() {
@Override
protected Bitmap doInBackground(String... strings) {
return getBitmap(strings[0]);
}
@Override
protected void onPostExecute(Bitmap bitmap) {
callback.loadImageSuccess(imageUrl,bitmap);
}
}.execute(imageUrl);
}
public interface Callback{
public void loadImageSuccess(String ImageUrl,Bitmap bitmap);
}
//吧线程吞掉
//因为是异步操作 不知道什么时候返回bitmap 所以不能返回结果
//加载图片大部分情况下是为了展示
public static void getBitmap(String imageUrl, final ImageView imageView){
new AsyncTask<String, Void, Bitmap>() {
@Override
protected Bitmap doInBackground(String... strings) {
return NetUtil.getBitmap(strings[0]);
}
@Override
protected void onPostExecute(Bitmap bitmap) {
imageView.setImageBitmap(bitmap);
}
}.execute(imageUrl);
}
//网络请求一张图片
public static Bitmap getBitmap(String path){
try {
HttpURLConnection urlConnection = (HttpURLConnection) new URL(path).openConnection();
int responseCode = urlConnection.getResponseCode();
if(responseCode == 200){
//调用转换字符串的方法
Bitmap bitmap = BitmapFactory.decodeStream(urlConnection.getInputStream());
return bitmap;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public static String getstring(InputStream is) throws IOException {
StringBuilder builder = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
for (String i = bufferedReader.readLine();i != null;i=bufferedReader.readLine()){
builder.append(i);
}
return builder.toString();
}
}