//OkHttp(网络请求框架)
implementation 'com.squareup.okhttp3:okhttp:3.12.1'
debugImplementation 'com.squareup.okhttp3:logging-interceptor:3.12.1'
//Gson(谷歌官方 Json 库)
implementation 'com.google.code.gson:gson:2.8.5'
//
implementation('com.github.bumptech.glide:glide:4.9.0') {
exclude group: "com.android.support"
}
在res目录下新建xml文件夹 文件名为network_config.xml
<network-security-config>
<base-config cleartextTrafficPermitted="true" />
network-security-config>
android:networkSecurityConfig="@xml/network_config"
private ImageJson LoadJson() {
//第一步:请求HTTPS,需配置network_config.xml
//第二步;请求接口(https://api.thecatapi.com/v1/images/search) 获取数据
//1.添加依赖
//2.OKHTTP操作
//异步
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url("https://api.thecatapi.com/v1/images/search")
.build();
ArrayList<ImageJson> list = null;
try {
Response response = okHttpClient.newCall(request).execute();
String string = response.body().string();
//解析json
Gson gson = new Gson();
list = gson.fromJson(string, new TypeToken<List<ImageJson>>() {
}.getType());
} catch (IOException e) {
e.printStackTrace();
}
Log.d("aaa1",list.get(0).toString());
return list.get(0);
}
Glide.with(itemView.getContext())
.load(url)
.diskCacheStrategy(DiskCacheStrategy.ALL)//采用了缓存策略
.placeholder(R.mipmap.ic_launcher)//还没加载出来的时候展示
.error(R.drawable.ic_close_black_24dp)//错误时展示
.into(image);
recy.setLayoutManager(new StaggeredGridLayoutManager(3,
StaggeredGridLayoutManager.VERTICAL));
recy.setHasFixedSize(true);
RecyAdapter adapter = new RecyAdapter(lists);
recy.setAdapter(adapter);
public class DownloadActivity extends AppCompatActivity {
private static final String JSONINFO = "jsoninit";
Button bt1;
Button tj;
EditText et;
TextView tv;
int count = 0;
private ArrayList<String> list = new ArrayList<String>();;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download);
bt1 = findViewById(R.id.bt1);
et = findViewById(R.id.et_te);
tv= findViewById(R.id.tv_text);
tj = findViewById(R.id.bt_tj);
tj.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String s = et.getText().toString();
if (s!=null&&!s.equals("")){
count = Integer.parseInt(s);
}
tj.setEnabled(false);
MyAsy myAsy = new MyAsy();
myAsy.execute();
}
});
bt1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(DownloadActivity.this, MainActivity.class);
intent.putExtra("list", list);
startActivity(intent);
}
});
}
//AsyncTask
class MyAsy extends AsyncTask<String, Integer, String>{
@Override
protected String doInBackground(String... strings) {
int i=0;
while (i<count){
ImageJson imageJson = LoadJson();
// Log.d("aaa", imageJson.toString());
list.add(imageJson.getUrl());
i++;
publishProgress(i);
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
int i =values[0];
String s = tv.getText().toString();
s = i+"--"+list.get(i-1)+"\n"+s;
tv.setText(s);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
bt1.setEnabled(true);
}
}
private ImageJson LoadJson() {
//第一步:请求HTTPS,需配置network_config.xml
//第二步;请求接口(https://api.thecatapi.com/v1/images/search) 获取数据
//1.添加依赖
//2.OKHTTP操作
//异步
OkHttpClient okHttpClient = new OkHttpClient();
Request request = new Request.Builder()
.url("https://api.thecatapi.com/v1/images/search")
.build();
ArrayList<ImageJson> list = null;
try {
Response response = okHttpClient.newCall(request).execute();
String string = response.body().string();
Gson gson = new Gson();
list = gson.fromJson(string, new TypeToken<List<ImageJson>>() {
}.getType());
} catch (IOException e) {
e.printStackTrace();
}
Log.d("aaa1",list.get(0).toString());
return list.get(0);
}
}
public class MainActivity extends AppCompatActivity {
private static final String JSONINFO = "jsoninit";
private ArrayList<String> lists;
private RecyclerView recy;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Log.d("aaa1", recy.getTransitionName());
Intent intent = getIntent();
if (intent != null) {
Serializable list = intent.getSerializableExtra("list");
lists = (ArrayList<String>) list;
}
Log.d("aaa1", lists.toString());
initview();
}
private void initview() {
recy = findViewById(R.id.recy123);
recy.setLayoutManager(new StaggeredGridLayoutManager(3,
StaggeredGridLayoutManager.VERTICAL));
recy.setHasFixedSize(true);
RecyAdapter adapter = new RecyAdapter(lists);
recy.setAdapter(adapter);
}
}
public class ImageJson implements Serializable {
private String id;
private String url;
private int width;
private int height;
@Override
public String toString() {
return "ImageJson{" +
"id='" + id + '\'' +
", url='" + url + '\'' +
", width=" + width +
", height=" + height +
'}';
}
........
}
public class RecyAdapter extends RecyclerView.Adapter<RecyAdapter.BaseViewHolder>{
private Resources res;
private ArrayList<String> dataList ;
public RecyAdapter(ArrayList<String> list){
dataList = list;
}
@NonNull
@Override
public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
return new OneViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.recy_plur,parent,false));
}
@Override
public void onBindViewHolder(@NonNull BaseViewHolder holder, int position) {
holder.setData(dataList.get(position));
}
@Override
public int getItemCount() {
return dataList != null ? dataList.size() : 0;
}
///这个BaseViewHolder好像没有发挥声明作用
public class BaseViewHolder extends RecyclerView.ViewHolder {
public BaseViewHolder(@NonNull View itemView) {
super(itemView);
}
void setData(Object data){
}
}
private class OneViewHolder extends BaseViewHolder{
ImageView image;
public OneViewHolder(@NonNull View view) {
super(view);
image = view.findViewById(R.id.recyImage);
int width = ((Activity) image.getContext()).getWindowManager().getDefaultDisplay().getWidth();
ViewGroup.LayoutParams params = image.getLayoutParams();
params.width = width/3;
params.height = (int) (200+Math.random()*200);
image.setLayoutParams(params);
res = itemView.getContext().getResources();
}
@Override
void setData(Object data) {
if (data != null) {
String url = (String) data;
Glide.with(itemView.getContext())
.load(url)
.diskCacheStrategy(DiskCacheStrategy.ALL)
.placeholder(R.mipmap.ic_launcher)
.error(R.drawable.ic_close_black_24dp)
.into(image);
// Bitmap bitmap = BitmapFactory.decodeResource(res, R.mipmap.ic_launcher);
//异步获得bitmap图片颜色值
}
}
}
}
再见…