网络请求 当我们遇到调用很多次为了减少代码量和内存的占用 我们可以写一个工具类 每次需要我们可以直接调用 单例模式
程序员文章站
2022-05-25 23:47:03
...
package com.example.day8_2;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.widget.ImageView;
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
public class Util {
//单例
private static Util instance;
//私有构造方法
private Util() {
}
//提供方法,获取对象
public static Util getInstance() {
if(instance == null) {
instance = new Util();
}
return instance;
}
public static T jiexi(String lujing,Class clazz){
T t = (T) new Gson().fromJson(getRequest(lujing), clazz);
return t;
}
//普通get请求
public static String getRequest(String UrlPath){
try {
URL url = new URL(UrlPath);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
int responseCode = urlConnection.getResponseCode();
if(responseCode == 200){
String result = Tostring(urlConnection.getInputStream());
return result;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static void bitmap(String url, final ImageView imageView){
new AsyncTask<String, Void, Bitmap>() {
@Override
protected Bitmap doInBackground(String... strings) {
Bitmap bitmap = Util.getBitmap(strings[0]);
return bitmap;
}
@Override
protected void onPostExecute(Bitmap bitmap) {
imageView.setImageBitmap(bitmap);
}
}.execute(url);
}
public static Bitmap getBitmap(String url){
try {
URL urll = new URL(url);
HttpURLConnection urlConnection = (HttpURLConnection) urll.openConnection();
int responseCode = urlConnection.getResponseCode();
if(responseCode == 200){
Bitmap bitmap = BitmapFactory.decodeStream(urlConnection.getInputStream());
return bitmap;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static String Tostring(InputStream inputStream) throws IOException {
StringBuilder stringBuilder = new StringBuilder();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
for(String mmp = bufferedReader.readLine();mmp!=null;mmp = bufferedReader.readLine()){
stringBuilder.append(mmp);
}
return stringBuilder.toString();
}
}