Android网络连线之HttpURLConnection【从网页获取图片 demo】

Android网络连线之HttpURLConnection【从网页获取图片 demo】,第1张

概述从网页获取图片效果是这样,下面是代码:layout<?xmlversion="1.0"encoding="utf-8"?><LinearLayoutxmlns:android="http://schemas.android.com/apkes/android"android:orientation="vertical"android:layout_width=&quo 从网页获取图片

效果是这样,下面是代码:

layout

<?xml version="1.0" enCoding="utf-8"?><linearLayout xmlns:androID="http://schemas.androID.com/apk/res/androID"    androID:orIEntation="vertical"    androID:layout_wIDth="match_parent"    androID:layout_height="match_parent" >    <EditText        androID:layout_wIDth="match_parent"        androID:layout_height="wrap_content"        androID:ID="@+ID/et_target"        androID:text="https://bkimg.cdn.bcebos.com/pic/574e9258d109b3de43046931c3bf6c81800a4c34?x-bce-process=image/resize,m_lfit,w_500,h_500,limit_1"        />    <button        androID:layout_wIDth="match_parent"        androID:layout_height="wrap_content"        androID:text="visualizer"        androID:onClick="visualizer"/>    <ImageVIEw        androID:layout_wIDth="wrap_content"        androID:layout_height="wrap_content"        androID:ID="@+ID/iv_result"        /></linearLayout>

StreamUtility(把流写在文件上)

public class StreamUtility {    public static voID writeStream2file (inputStream in, file file) throws Exception {        fileOutputStream outputStream = new fileOutputStream(file);        int len= -1;        byte[] buffer = new byte[1024];        while ((len= in.read(buffer)) !=-1){            outputStream.write(buffer,0,len);        }        outputStream.close();        in.close();    }}

Mainactivity.java

因为子线程不能更新ui,这里有两种方法

1.线程之间通讯构建第三方,利用handler传给主线程再更新ui
2.用runonUIThread方法,直接在子线程更新ui

public class MainActivity extends AppCompatActivity {    private EditText et_target;    private ImageVIEw iv_result;    private Handler handler =new Handler(){        @OverrIDe        public voID handleMessage( Message msg) {            switch (msg.what){                case RESPONSE_SUCCESS:                    Bitmap result = (Bitmap) msg.obj;                    iv_result.setimageBitmap(result);                    break;                case RESPONSE_Failed:                    Toast.makeText(MainActivity.this, "失败"+msg.arg1, Toast.LENGTH_SHORT).show();                    break;                case RESPONSE_EXCEPTION:                    Toast.makeText(MainActivity.this, "异常", Toast.LENGTH_SHORT).show();                    break;            }        }    };    private  final int RESPONSE_SUCCESS=1;    private  final int RESPONSE_Failed=2;    private  final int RESPONSE_EXCEPTION=3;    @OverrIDe    protected voID onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentVIEw(R.layout.activity_main);        et_target = (EditText) findVIEwByID(R.ID.et_target);        iv_result = (ImageVIEw) findVIEwByID(R.ID.iv_result);    }    public voID visualizer(VIEw vIEw) {        final String path = et_target.getText().toString().trim();            final file file = new file(getCacheDir(), Base64.encodetoString(path.getBytes(),Base64.DEFAulT));/*缓存cache*//*现在没产生文件,写名,开流时候才产生*/        /*base64应用原因 1.转换成的字符串没有特殊字符2.加密好的也是唯一的,不能重复3.加密后的固定长度*/        if (file.exists() && file.length()>0){            Bitmap bitmap = BitmapFactory.decodefile(file.getabsolutePath());            iv_result.setimageBitmap(bitmap);            System.out.println("-----------------cache");            return;        }        new Thread(){            @OverrIDe            public voID run() {                httpURLConnection connection = null;                try {                    URL url = new URL(path);                     connection = (httpURLConnection) url.openConnection();                    connection.setRequestMethod("GET");                    connection.setConnectTimeout(5000);                    int code = connection.getResponseCode();                    if (code == 200){                        inputStream inputStream = connection.getinputStream();                        StreamUtility.writeStream2file(inputStream,file);/*把流写入file文件上*/                        /*Message message = new Message();*//*new是最慢的*/                        final Bitmap bitmap = BitmapFactory.decodefile(file.getabsolutePath());/*从本地拿,绝对路径*/                        System.out.println("-----------------newload");                                                runOnUiThread(new Runnable() {                            @OverrIDe                            public voID run() {                                iv_result.setimageBitmap(bitmap);                            }                        });                  /*如果只更新ui用runOnUiThread,如果给主线程发数据只能用handler*/                        /*iv_result.setimageBitmap(BitmapFactory.decodeStream(inputStream));*//*位图,容易崩溃*/                    }else {                        Message msg = Message.obtain();                        msg.arg1=code;                        msg.what=RESPONSE_Failed;                        handler.sendMessage(msg);                    }                } catch (Exception e) {                    handler.sendEmptyMessage(RESPONSE_EXCEPTION);                    e.printstacktrace();                } finally {                    if (connection != null)                    connection.disconnect();                }            }        }.start();    }}

最后在androIDmanifest加上网络权限

 <uses-permission androID:name="androID.permission.INTERNET"/>
总结

以上是内存溢出为你收集整理的Android网络连线之HttpURLConnection【从网页获取图片 demo】全部内容,希望文章能够帮你解决Android网络连线之HttpURLConnection【从网页获取图片 demo】所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/web/1062841.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-26
下一篇 2022-05-26

发表评论

登录后才能评论

评论列表(0条)

保存