OkHttp 安卓开发中请求图片的Demo
开启网络权限
<uses-permission android:name="android.permission.INTERNET" />
gradle新增okhttp依赖
implementation group: 'com.squareup.okhttp3', name: 'okhttp', version: '3.10.0'
MainActivity.java代码
package com.example.okhttpdemo;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
/**
* OkHttp 加载图片 异步或同步请求
* @author cst
*/
public class MainActivity extends AppCompatActivity {
private ImageView imageView;
private TextView title;
@Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
/**
* 初始化
*/
private void init() {
imageView = (ImageView) findViewById(R.id.image);
title = findViewById(R.id.title);
Button getDefaultImageBtn = findViewById(R.id.get_btn);
Button getSynImageBtn = findViewById(R.id.get_syn_btn);
Button getImageBtn = findViewById(R.id.image_url_btn);
//初始化按钮单击监听器
getDefaultImageBtn.setOnClickListener(v -> showImage("https://www.cstweb.top/wp-content/uploads/2021/09/WBVEM0EQSQEXVDIDDUJU-1-768x810.jpg"));
getSynImageBtn.setOnClickListener(v -> showImageBySyn("https://www.cstweb.top/wp-content/uploads/2021/09/java-think-721x1024.png"));
getImageBtn.setOnClickListener(v -> showInputDialog());
}
/**
* 加载图片(异步请求)
* @param imageURL
*/
public void showImage(String imageURL){
Handler handler=new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(Message msg) {
if (msg.what == 1){
byte[]result= (byte[]) msg.obj;
Bitmap bitmap=BitmapFactory.decodeByteArray(result,0,result.length);
imageView.setImageBitmap(bitmap);
title.setText("加载完成");
}
return false;
}
});
Request request = null;
OkHttpClient client=new OkHttpClient();
try {
request = new Request.Builder().url( imageURL ).build();
} catch (IllegalArgumentException e) {
Toast.makeText(MainActivity.this, "无效的URL地址", Toast.LENGTH_SHORT).show();
return;
}
imageView.setImageDrawable(null);
title.setText("加载中.... ");
client.newCall(request).enqueue(new Callback() {
@Override
public void onResponse(Call call, Response response) throws IOException {
Message message=handler.obtainMessage();
if (response.isSuccessful()){
message.what=1;
message.obj=response.body().bytes();
handler.sendMessage(message);
}else{
handler.sendEmptyMessage(0);
}
}
@Override
public void onFailure(Call call, IOException e) {
runOnUiThread(() -> {
title.setText("加载失败...");
imageView.setImageDrawable(null);
});
}
});
}
/**
* 加载图片(同步请求)
* @param imageURL
*/
public void showImageBySyn(String imageURL){
imageView.setImageDrawable(null);
new Thread(new Runnable() {
@Override
public void run() {
OkHttpClient client = new OkHttpClient.Builder().readTimeout(5, TimeUnit.SECONDS).build();
Request request = null;
try {
request = new Request.Builder().url( imageURL ).build();
} catch (IllegalArgumentException e) {
Toast.makeText(MainActivity.this, "无效的URL地址", Toast.LENGTH_SHORT).show();
return;
}
runOnUiThread(() -> title.setText("同步方式, 加载中..."));
Call call = client.newCall(request);
try {
Response response = call.execute();
byte[] result = response.body().bytes();
Bitmap bitmap=BitmapFactory.decodeByteArray(result,0,result.length);
runOnUiThread(() -> {
imageView.setImageBitmap(bitmap);
title.setText("加载完成");
});
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
/**
* URL输入对话框
* 通过输入URL显示相应的图片
**/
public void showInputDialog() {
View view = LayoutInflater.from(this).inflate(R.layout.dialog_input_url, null, false);
final AlertDialog dialog = new AlertDialog.Builder(this).setView(view).create();
Button getImage = view.findViewById(R.id.get_image);
Button cancelBtn = view.findViewById(R.id.cancel);
getImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
EditText contentText = view.findViewById(R.id.url_text);
String URL = contentText.getText().toString().trim();
showImage(URL);
dialog.dismiss();
}
});
cancelBtn.setOnClickListener(v -> dialog.dismiss());
dialog.show();
}
}
实现效果图
Best Dating Sites for Real Relationships in 2022 click here
buy tadalafil 40mg pill – cialis 5mg price order cialis generic
plaquenil 400mg pill – hydroxychloroquine 400mg sale hydroxychloroquine for sale
buy ivermectin uk – ivermectin 3 mg without a doctor prescription ivermectin 6 mg without prescription
buy cephalexin 250mg pills – erythromycin 500mg pill brand erythromycin
generic sildenafil – nolvadex 10mg oral buy generic antabuse 250mg
budesonide generic – buy cefuroxime generic purchase cefuroxime generic
careprost medication – buy bimatoprost pill desyrel 100mg for sale
order viagra 100mg pill – cheap viagra for sale ranitidine medication
cialis coupon cvs – purchase tadalafil stromectol ivermectin tablets
tadalafil 5mg pill – non prescription ed drugs buy erectile dysfunction pills
casino online gambling – best real money casino buy prednisone 10mg generic
generic prednisone 5mg – buy accutane for sale buy generic isotretinoin 40mg
cheap amoxil pill – buy amoxicillin 500mg pill order viagra 50mg without prescription
buy cialis 40mg – purchase cialis sale buy tadalafil 10mg pills
ivermectin lotion price – order zithromax 250mg without prescription zithromax 250mg ca
order zithromax 250mg pills – buy methylprednisolone 4mg fda medrol
baricitinib 2mg drug – order chloroquine generic priligy over the counter
metformin for sale online – canadian pharmacy online coupon cost lipitor 40mg
amlodipine over the counter – purchase amlodipine online prilosec online
order metoprolol online cheap – tenormin 50mg brand female cialis cvs
cialis 5mg pill – buy cialis 20mg pills sildenafil for men over 50
ivermectin topical – ivermectin online pharmacy stromectol oral
buy clomid 50mg without prescription – order clomid 50mg online cheap cetirizine 10mg over the counter
clarinex 5mg cost – cost desloratadine triamcinolone generic
generic misoprostol 200mcg – cytotec 200mcg sale synthroid 75mcg sale
viagra generic – brand name viagra order neurontin online
generic cialis cost – cialis order cenforce 100mg price
buy diltiazem without prescription – order allopurinol generic buy acyclovir 800mg online cheap
atarax 10mg ca – purchase hydroxyzine sale buy crestor 10mg online
ezetimibe drug – ezetimibe canada buy citalopram without prescription
sildenafil 150mg pills – viagra for men generic flexeril 15mg
sildenafil overnight – buy tadalafil pills cialis online canada
toradol 10mg pills – buy toradol 10mg ozobax sale
colchicine online order – order inderal sale strattera 25mg drug
order viagra 100mg generic – viagra 100mg sale sildenafil 50mg for sale
purchase nexium online cheap – purchase promethazine without prescription phenergan without prescription
tadalafil medication – Generic cialis next day delivery generic cialis 40mg
Gdje mogu naučiti forex trgovanje. https://hr.forex-stock-bitcoin-brokers.com
provigil 100mg usa – buying ed pills online male ed drugs
accutane 10mg for sale – brand amoxicillin 500mg azithromycin 500mg sale
lasix for sale – viagra 50mg us buy viagra 50mg online cheap
order cialis pills – viagra 50mg without prescription sildenafil pills 150mg
order tadalafil 10mg sale – order coumadin 5mg pills coumadin 5mg price
order topamax 200mg – order imitrex 50mg generic buy imitrex 50mg generic
cannahome dark market cannahome market darknet
asap market versus market
cypher market url versus market link
darkfox market world market link
asap market url cypher market url
cannahome market url cypher market link
cypher market heineken express
versus market link cannazon market url
cannahome market url darkfox market link
avodart 0.5mg without prescription – tadalafil 20mg drug order tadalafil 20mg
tor market url dark web link
drug markets onion dark web drug marketplace
dark market 2022 darknet websites
darkmarket list darkmarket link
darkmarket darkmarket 2022
drug markets dark web dark market 2022
spurdomarket market top darknet markets 2022
darknet market deep web drug store
darknet market list 2021 cannahome market darknet
darknet websites deep web drug markets
darknet market darknet market list
dark market onion tor dark web
darknet market prices spurdomarket darknet market
darknet market darknet websites
cypher link deep web drug links
darknet marketplace dark web market
darknet credit card market guide to darknet markets
darknet drug store dark market 2022
tor market url dark web drug marketplace
dark market link dark market link
dark market list tor market links
tor2door darknet market asap market darknet
dark web market links reddit darknet market list
dark market link darknet drug links
wall street market darknet reddit bohemia link
dark web link dark web market links
cypher market cannazon link
deep web drug store tor markets 2022
darknet market drug markets onion
darkmarket 2022 tor market links
cypher market darknet uk darknet markets
darknet websites darkmarket 2022
darknet drug market deep web drug store
dark web link tor market url
dark web drug marketplace dark markets 2022
deep web drug links darkmarket 2022
darknet market prices incognito link
tor marketplace darknet drug links
cannahome market url cannazon link
dark market list deep web drug url
dark web market list bitcoin dark web
versus project market url daeva darknet market
dark web sites dark market onion
best darknet markets darknet market
cypher market darknet asap market
darkmarket darknet market list
how to get to darknet market deep web drug url
darknet websites dark web markets
bitcoin dark web deep web drug url
tor market url dark web market
buy viagra 100mg without prescription – viagra us cialis coupon walmart
tor dark web dark market link
deep web drug url monopoly market link
dark web sites deep web drug links
darknet market onion links guide to darknet markets
darknet websites tor dark web
darknet websites darknet drug store
archetyp market black market prescription drugs for sale
darknet drug market dark market url
darkmarket deep web drug store
tor dark web dark web market links
empire market darknet darknet market search
darknet drug links darknet drug links
tor marketplace dream market darknet
dark web markets darknet market list
darkmarket dark web market
darknet drug links darkmarket link
dark web link drug markets dark web
wallstreet market darknet market stats
spurdomarket market grams darknet market search engine
dark web drug marketplace darknet market
deep web drug markets darknet market links
darknet market lists tor dark web
drug markets onion dark market list
darknet market guide reddit darkfox market
darkmarket link darkmarket list
tor market url dark market list
dark web market darknet market
darknet drug links samsara market darknet
darknet dream market link darknet market status
dark market url bitcoin dark web
tor marketplace samsara darknet market
tor market url dark market link
bitcoin dark web tor markets 2022
tor markets links darknet market
darkmarket 2021 active darknet markets
dark market url tor market links
tor marketplace darkmarket
darknet drug market darknet drug market
darkmarket url drug markets onion
liberty link best australian darknet market
dark web markets bitcoin dark web
dark web markets dark markets 2022
torrez link darknet stock market
monopoly market url best darknet market 2021 reddit
tor markets links drug markets onion
deep web drug markets deep web drug links
versus link wall street market darknet
dark market url darkmarket 2022
best darknet markets darkmarket link
darkmarket url dark web market list
dark market onion dark web drug marketplace
dark market darkmarket list
darknet marketplace best darknet markets
darkmarket url bitcoin dark web
liberty darknet market best darknet market 2021 reddit
daeva market link Spurdomarket market url
dark web markets darknet market
dark market 2022 dark web market
bohemia market url silk road darknet market