您当前的位置: 首页 > 学无止境 > 心得笔记 网站首页心得笔记
36_网络图片查看器
发布时间:2021-02-22 14:48:10编辑:雪饮阅读()
tomcat环境搭建
下载如apache-tomcat-7.0.108-windows-x64.zip解压后进入其bin目录运行startup.bat
按照提示需要配置JAVA_HOME环境变量
这里配置JAVA_HOME环境变量时变量值可以不用直接进入bin目录,在bin所在目录即可。
配置结束后关闭之前的命令行窗口重新开一个命令行窗口重复上面的操作,如无其它提示,则进入如下界面,同意下其它防火墙的允许选项即可
然后浏览器进入http://localhost:8080/即可看到搭建成功后的tomcat环境
接下来是默认的tomcat根目录,在刚才的tomcat的bin目录的上级目录中的webapps/ROOT目录就是默认的tomcat根目录,如:
D:\apache-tomcat-7.0.108-windows-x64\apache-tomcat-7.0.108\webapps\ROOT
然后在这个目录比如放置一个test.png,然后在浏览器中访问如:
http://localhost:8080/test.png,就可以看到图片被请求到了
实现网络图片查看器
以上面这个可访问的图片链接为例,只是上面这个链接中主机名是localhost,localhost指的是本地的意思,那么如果按照localhost来访问则在安卓设备中相当于访问安卓本机中的tomcat服务,所以我们必须知道我们物理机的局域网ip地址,用此ip地址来提供该localhost如:
则我们要访问的地址应该是http://192.168.5.30:8080/test.png
接下来大概布局下主界面activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/please_input_address" />
<EditText
android:id="@+id/et_address"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="http://192.168.5.30:8080/test.png"
android:lines="2" />
<Button
android:id="@+id/bt_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/bt_view_text" />
<ImageView
android:id="@+id/iv_image"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="center" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/please_input_address" />
<EditText
android:id="@+id/et_address"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="http://192.168.5.30:8080/test.png"
android:lines="2" />
<Button
android:id="@+id/bt_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/bt_view_text" />
<ImageView
android:id="@+id/iv_image"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:scaleType="center" />
</LinearLayout>
接下来是布局界面上元素的相关值values/strings.xml:(其实这一步也可以和上一步整合,具体看个人喜好)
<resources>
<string name="app_name">My Application Image</string>
<string name="please_input_address">请输入图片的地址</string>
<string name="bt_view_text">查看</string>
</resources>
由于网络请求图片返回的是图片对应的流,接下来再实现一个输入流转换为字节数组的方法。直接放在MainActivity.java同目录吧,则如:StreamTool.java:
package com.example.myapplicationimage;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
public class StreamTool {
/**
* 把一个inputstream里面的内容转化成一个byte[]
*/
public static byte[] getBytes(InputStream is) throws Exception{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while((len = is.read(buffer))!=-1){
bos.write(buffer, 0, len);
}
is.close();
bos.flush();
byte[] result = bos.toByteArray();
System.out.println(new String(result));
return result;
}
}
然后实现一个获取网络图片的方法,同样放在MainActivity.java同目录吧,则如:ImageUtil.java:
package com.example.myapplicationimage;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
public class ImageUtil {
/**
* 获取网络address地址对应的图片
* @param address
* @return bitmap的类型
*/
public static Bitmap getImage(String address) throws Exception{
//ͨ通过代码模拟器浏览器访问图片的流程
URL url = new URL(address);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(5000);
//获取服务器返回回来的流
InputStream is = conn.getInputStream();
byte[] imagebytes = StreamTool.getBytes(is);
Bitmap bitmap = BitmapFactory.decodeByteArray(imagebytes, 0, imagebytes.length);
return bitmap;
}
}
然后实现“查看”按钮的主方法MainActivity.java:
package com.example.myapplicationimage;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.IOException;
import java.net.SocketTimeoutException;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private EditText mEtAddress;
private Button mBtView;
private ImageView mIvView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEtAddress = (EditText) this.findViewById(R.id.et_address);
mBtView = (Button) this.findViewById(R.id.bt_view);
mIvView = (ImageView) this.findViewById(R.id.iv_image);
mBtView.setOnClickListener(this);
}
//高版本安卓使用okhttp报错:android下的android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork错误
//这里获取网络图片就用到了okhttp,安卓9也算是高版本了,毕竟我这里也的确报类似这个错误了
//解决方法有两个:
//(1)java创建个线程,在线程中去httpClient访问网络。
//(2)在请求网络的方法前用如下这两个注解,并在方法体中具体访问网络处先执行如下两行代码:
//StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
//StrictMode.setThreadPolicy(policy);
@TargetApi(Build.VERSION_CODES.GINGERBREAD)
@SuppressLint("NewApi")
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt_view:
//按钮对应的点击事件
String address = mEtAddress.getText().toString().trim();
if("".equals(address)){
Toast.makeText(this, "图片地址不能为空", Toast.LENGTH_SHORT).show();
return;
}
try {
StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Bitmap bitmap = ImageUtil.getImage(address);
mIvView.setImageBitmap(bitmap);
} catch (Exception e) {
if(e instanceof SocketTimeoutException){
Toast.makeText(this, "网络连接超时", Toast.LENGTH_SHORT).show();
}else if(e instanceof IOException){
Toast.makeText(this, "读取数据错误 ", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(this, "未知错误 ", Toast.LENGTH_SHORT).show();
}
e.printStackTrace();
}
break;
}
}
}
最后,就是清单文件了,网络请求实在是比较麻烦,清单文件中的处理也有所不同,这里使用一种比较简单的方式,则如:AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.myapplicationimage">
<!--
访问网络必须要在清单文件中加入如下声明,该声明不会出现在app的权限勾选列表里,即不用为app勾选这个权限
只要声明了,就可以直接使用了
-->
<uses-permission android:name="android.permission.INTERNET"/>
<!--
在高版本的安卓中对于http的访问可能会出现下面这个错误
W/System.err: java.io.IOException: Cleartext HTTP traffic to **** not permitted
可以更换为更安全的https,若不想更换为https,则也可以在application标签中添加如下属性来解决:
android:usesCleartextTraffic="true"
-->
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MyApplicationImage"
android:usesCleartextTraffic="true"
>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
最后就是验货了,部署到设备中,点击查看按钮就可以获取到刚才tomcat中的那个test.png了
关键字词:android,网络,图片