当前位置: 首页 > news >正文

Android之网络操作 - 从网络获取图片或网页

1.在Java中操作显示网络图片

public class ImageRequest { /** * @param args */ public static void main(String[] args) throws Exception { //构造一个URL对象 URL url = new URL("http://www.baidu.com/img/baidu_sylogo1.gif"); //使用openConnection打开URL对象 HttpURLConnection conn = (HttpURLConnection)url.openConnection(); //使用Http协议,设置请求方式为GET conn.setRequestMethod("GET"); //设置链接超时异常,5s conn.setConnectTimeout(5 * 1000); //通过输入流获取图片数据 InputStream inStream = conn.getInputStream(); //获取到图片的二进制数据 byte[] data = readInputStream(inStream); //构造一个文件,保存图片到项目的根目录下 File imageFile = new File("baidu_logo.jpg"); //构造一个文件输出流FileOutputStream FileOutputStream outStream = new FileOutputStream(imageFile); //把文件数据写入到输出流 outStream.write(data); outStream.close(); } /** * 从输入流里面得到返回为二进制的数据 * @param inStream 输入流 * @return byte[] 二进制数据 * @throws Exception */ public static byte[] readInputStream(InputStream inStream) throws Exception { //构造一个ByteArrayOutputStream ByteArrayOutputStream outStream = new ByteArrayOutputStream(); //设置一个缓冲区 byte[] buffer = new byte[1024]; int len = 0; //判断输入流长度是否等于-1,即非空 while( (len=inStream.read(buffer)) != -1 ) { //把缓冲区的内容写入到输出流中,从0开始读取,长度为len outStream.write(buffer, 0, len); } //关闭输入流 inStream.close(); return outStream.toByteArray(); } }

2.Android中显示图片:

(1)ImageShowActivity.java

public class ImageShowActivity extends Activity { private static final String TAG = "ImageShowActivity"; private EditText pathText; private ImageView imageView; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //得到EditText,ImageView与Button pathText = (EditText) this.findViewById(R.id.urlpath); imageView = (ImageView) this.findViewById(R.id.imageView); Button button = (Button)this.findViewById(R.id.button); //设置Button监听 button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //获取EditText里面的地址 String path = pathText.getText().toString(); try { //得到图片的二进制数据 byte[] data = ImageService.getImage(path); //图片处理 Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);//生成位图 //显示图片 imageView.setImageBitmap(bitmap); } catch (Exception e) { //出错的时候提示错误信息 Toast.makeText(ImageShowActivity.this, R.string.error, 1).show(); //Log里面打印错误信息 Log.e(TAG, e.toString()); } } }); } }

(2)编写一个流处理工具类,StreamTool.java

public class StreamTool { /** * 从输入流里面得到返回为二进制的数据 * @param inStream 输入流 * @return byte[] 二进制数据 * @throws Exception */ public static byte[] readInputStream(InputStream inStream) throws Exception { //构造一个ByteArrayOutputStream ByteArrayOutputStream outStream = new ByteArrayOutputStream(); //设置一个缓冲区 byte[] buffer = new byte[1024]; int len = 0; //判断输入流长度是否等于-1,即非空 while( (len=inStream.read(buffer)) != -1 ) { //把缓冲区的内容写入到输出流中,从0开始读取,长度为len outStream.write(buffer, 0, len); } //关闭输入流 inStream.close(); return outStream.toByteArray(); } }

(3)编写一个图片处理类,打开URL,获取输入流等操作

public class ImageService { public static byte[] getImage(String path) throws Exception { //构造一个URL对象 URL url = new URL("http://www.baidu.com/img/baidu_sylogo1.gif"); //使用openConnection打开URL对象 HttpURLConnection conn = (HttpURLConnection)url.openConnection(); //使用Http协议,设置请求方式为GET conn.setRequestMethod("GET"); //设置链接超时异常,5s conn.setConnectTimeout(5 * 1000); //通过输入流获取图片数据 InputStream inStream = conn.getInputStream(); //返回图片的二进制数据 return StreamTool.readInputStream(inStream); } }

注意别忘记在AndroidManifest.xml文件中添加访问网络的权限:

<uses-permission android:name="android.permission.INTERNET"/>

3.在Android中显示网页代码:通过滚动条视图(ScrollView)工具显示代码

(1)main.xml

<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <ScrollView android:layout_width="fill_parent" android:layout_height="fill_parent"> <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/textView" /> </ScrollView> </LinearLayout>

(2)与上面显示图片类似

public class MainActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView textView = (TextView)this.findViewById(R.id.textView); try { textView.setText(HtmlService.getHtml("http://www.sohu.com")); } catch (Exception e) { Log.e("MainActivity", e.toString()); Toast.makeText(MainActivity.this, "网络连接失败", 1).show(); } } }

public class HtmlService { public static String getHtml(String path) throws Exception { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("GET"); conn.setConnectTimeout(5 * 1000); //通过输入流获取html数据 InputStream inStream = conn.getInputStream(); //得到html的二进制数据 byte[] data = StreamTool.readInputStream(inStream); String html = new String(data, "gb2312"); return html; } }

public class StreamTool { /** * 从输入流中获取数据 * @param inStream 输入流 * @return * @throws Exception */ public static byte[] readInputStream(InputStream inStream) throws Exception { ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int len = 0; while( (len=inStream.read(buffer)) != -1 ) { outStream.write(buffer, 0, len); } inStream.close(); return outStream.toByteArray(); } }

相关文章:

  • OpenGL学习--开发环境
  • jQuery常用总结(转载)
  • Android之把从网络中获取的数据以XML与Json格式返回
  • 抗锯齿的BUG
  • Spring Boot 定时任务的使用
  • VC2012编译CEF3-转
  • Android之用HTTP的get,post,HttpClient三种方式向service提交文本数据
  • PCB原理图库
  • mysql相关故障
  • Win7 打开网页超级慢的解决方案
  • Java并发和多线程3:线程调度和有条件取消调度
  • Android之使用Http协议实现文件上传功能
  • poi API大全
  • Authentication和Authrization(上)
  • std::bind()图解
  • 03Go 类型总结
  • mockjs让前端开发独立于后端
  • nodejs:开发并发布一个nodejs包
  • php ci框架整合银盛支付
  • text-decoration与color属性
  • vue脚手架vue-cli
  • 解决iview多表头动态更改列元素发生的错误
  • 前端路由实现-history
  • 使用 QuickBI 搭建酷炫可视化分析
  • 世界编程语言排行榜2008年06月(ActionScript 挺进20强)
  • 小程序、APP Store 需要的 SSL 证书是个什么东西?
  • 学习使用ExpressJS 4.0中的新Router
  • 用jquery写贪吃蛇
  • 再次简单明了总结flex布局,一看就懂...
  • 在 Chrome DevTools 中调试 JavaScript 入门
  • 最简单的无缝轮播
  • 专访Pony.ai 楼天城:自动驾驶已经走过了“从0到1”,“规模”是行业的分水岭| 自动驾驶这十年 ...
  • ​2020 年大前端技术趋势解读
  • # Panda3d 碰撞检测系统介绍
  • (1)(1.19) TeraRanger One/EVO测距仪
  • (JS基础)String 类型
  • (ZT)一个美国文科博士的YardLife
  • (第61天)多租户架构(CDB/PDB)
  • (附源码)springboot“微印象”在线打印预约系统 毕业设计 061642
  • (附源码)springboot人体健康检测微信小程序 毕业设计 012142
  • (理论篇)httpmoudle和httphandler一览
  • (六)什么是Vite——热更新时vite、webpack做了什么
  • (深入.Net平台的软件系统分层开发).第一章.上机练习.20170424
  • (十六)串口UART
  • (使用vite搭建vue3项目(vite + vue3 + vue router + pinia + element plus))
  • (转)winform之ListView
  • .form文件_SSM框架文件上传篇
  • .Net 8.0 新的变化
  • .NET DataGridView数据绑定说明
  • .NET Framework 3.5中序列化成JSON数据及JSON数据的反序列化,以及jQuery的调用JSON
  • .NET MVC、 WebAPI、 WebService【ws】、NVVM、WCF、Remoting
  • .net Signalr 使用笔记
  • .net Stream篇(六)
  • .net 调用php,php 调用.net com组件 --
  • .NET 跨平台图形库 SkiaSharp 基础应用