java net 安卓_Java和Android Http连接程序:使用java.net.URL 下载服务器图片到客户端...

Java和Android Http连接程序:使用java.net.URL 下载服务器图片到客户端

本博客前面博文中利用org.apache.http包中API进行Android客户端HTTP连接的例子:

另一种常用的建立Http连接的常用方式是利用Java在JDK中提供的类,也即本文要演示的方法,本文的例子程序实现的功能是从服务器上下载图片到客户端。

关于两种建立Http连接方法(apache的包和JDK的包)的讨论可以看看后面的参考链接。

服务器端

服务器端需要准备图片,因为是Demo程序,所以我就准备了一张图片,然后把它放在Web Project的WebRoot路径下:

6cc1de9622fd98e84159beccd047dfe3.png

然后只要启动Tomcat,ipconfig查出ip地址,放在之后要用的路径中就可以了。

Java程序:Http连接 获取并下载服务器端图片

写一个工具类:

其中第一个方法根据给出的服务器地址及资源路径得到输入流:

public staticInputStream getInputStream(String path)

{

InputStream inputStream= null;

HttpURLConnection httpURLConnection= null;try{

URL url= newURL(path);if (null !=url)

{

httpURLConnection=(HttpURLConnection) url.openConnection();//设置连接网络的超时时间

httpURLConnection.setConnectTimeout(5000);//打开输入流

httpURLConnection.setDoInput(true);//设置本次Http请求使用的方法

httpURLConnection.setRequestMethod("GET");if (200 ==httpURLConnection.getResponseCode())

{//从服务器获得一个输入流

inputStream =httpURLConnection.getInputStream();

}

}

}catch(MalformedURLException e)

{

e.printStackTrace();

}catch(IOException e)

{

e.printStackTrace();

}returninputStream;

}

第二个方法根据输入流将文件存储在本地一个路径:

public static voidsaveInputStream(InputStream inputStream,

String saveToPath)

{byte[] data = new byte[1024];int len = 0;

FileOutputStream fileOutputStream= null;try{

fileOutputStream= newFileOutputStream(saveToPath);while (-1 != (len =inputStream.read(data)))

{

fileOutputStream.write(data,0, len);

}

}catch(IOException e)

{

e.printStackTrace();

}finally{if (null !=inputStream)

{try{

inputStream.close();

}catch(IOException e)

{

e.printStackTrace();

}

}if (null !=fileOutputStream)

{try{

fileOutputStream.close();

}catch(IOException e)

{

e.printStackTrace();

}

}

}

}

完整代码:

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

packagecom.meng.utils;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.net.HttpURLConnection;importjava.net.MalformedURLException;importjava.net.URL;public classHttpUtils

{public staticInputStream getInputStream(String path)

{

InputStream inputStream= null;

HttpURLConnection httpURLConnection= null;try{

URL url= newURL(path);if (null !=url)

{

httpURLConnection=(HttpURLConnection) url.openConnection();//设置连接网络的超时时间

httpURLConnection.setConnectTimeout(5000);//打开输入流

httpURLConnection.setDoInput(true);//设置本次Http请求使用的方法

httpURLConnection.setRequestMethod("GET");if (200 ==httpURLConnection.getResponseCode())

{//从服务器获得一个输入流

inputStream =httpURLConnection.getInputStream();

}

}

}catch(MalformedURLException e)

{

e.printStackTrace();

}catch(IOException e)

{

e.printStackTrace();

}returninputStream;

}public static voidsaveInputStream(InputStream inputStream,

String saveToPath)

{byte[] data = new byte[1024];int len = 0;

FileOutputStream fileOutputStream= null;try{

fileOutputStream= newFileOutputStream(saveToPath);while (-1 != (len =inputStream.read(data)))

{

fileOutputStream.write(data,0, len);

}

}catch(IOException e)

{

e.printStackTrace();

}finally{if (null !=inputStream)

{try{

inputStream.close();

}catch(IOException e)

{

e.printStackTrace();

}

}if (null !=fileOutputStream)

{try{

fileOutputStream.close();

}catch(IOException e)

{

e.printStackTrace();

}

}

}

}

}

HttpUtils.java

测试程序:

packagecom.meng.learn;importjava.io.InputStream;importcom.meng.utils.HttpUtils;public classHttpTest

{private static String URL_PATH = "http://192.168.11.6:8080/HelloWeb/android.jpg";public static voidmain(String[] args)

{

InputStream inputStream=HttpUtils.getInputStream(URL_PATH);

HttpUtils.saveInputStream(inputStream,"D:\\test1.jpg");

}

}

程序运行成功之后可以在指定路径下发现多了服务器端的那个图片。

Android客户端 Http连接:下载服务器端的图片到SD卡

Android的程序还需要考虑的几点是:

1.对SD卡的访问权限及操作。

2.为了不阻塞UI线程,下载操作放在独立的线程中。

3.加入了网路访问的检查,确认网络连接后再进行下载。

需要添加的权限

布局文件如下:

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

activity_image_download.xml

Activity中所做的就是按下按钮之后,连接服务器,将图片取出显示在ImageView里,同时存往SD卡的指定路径:

packagecom.mengexample.test;importjava.io.InputStream;importcom.windexample.utils.FileUtils;importcom.windexample.utils.HttpUtils;importandroid.app.Activity;importandroid.content.Context;importandroid.graphics.Bitmap;importandroid.graphics.BitmapFactory;importandroid.net.ConnectivityManager;importandroid.net.NetworkInfo;importandroid.os.AsyncTask;importandroid.os.Bundle;importandroid.view.View;importandroid.view.View.OnClickListener;importandroid.widget.Button;importandroid.widget.ImageView;importandroid.widget.TextView;importandroid.widget.Toast;public class ImageDownloadActivity extendsActivity

{private static String URL_PATH = "http://192.168.11.6:8080/HelloWeb/android.jpg";private TextView mTextView = null;private Button mButton = null;private ImageView mImageView = null;

@Overrideprotected voidonCreate(Bundle savedInstanceState)

{super.onCreate(savedInstanceState);

setContentView(R.layout.activity_image_download);

mTextView=(TextView) findViewById(R.id.info);

mTextView.setText(URL_PATH);

mButton=(Button) findViewById(R.id.btn);

mButton.setOnClickListener(mBtnClickListener);

mImageView=(ImageView) findViewById(R.id.image);

}private OnClickListener mBtnClickListener = newOnClickListener()

{

@Overridepublic voidonClick(View v)

{//首先确认网络连接

ConnectivityManager connectivityManager =(ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);

NetworkInfo networkInfo=connectivityManager

.getActiveNetworkInfo();if (null != networkInfo &&networkInfo.isConnected())

{newDownloadImageTask().execute(URL_PATH);

}else{

Toast.makeText(ImageDownloadActivity.this,"No network connection available", Toast.LENGTH_SHORT)

.show();

}

}

};private class DownloadImageTask extends AsyncTask{

@OverrideprotectedBitmap doInBackground(String... params)

{

String path= params[0];

InputStream inputStream=HttpUtils.getInputStream(path);//从输入流得到位图

Bitmap bitmap =BitmapFactory.decodeStream(inputStream);//将图像存储到SD卡FileUtils.saveToSDCard(bitmap,"TestImage", "android.jpg");returnbitmap;

}

@Overrideprotected voidonPostExecute(Bitmap result)

{//将图像显示出来

mImageView.setImageBitmap(result);

}

}

}

其中用到的两个工具类:

建立连接并获取输入流的方法和Java代码中的一样:

packagecom.windexample.utils;importjava.io.IOException;importjava.io.InputStream;importjava.net.HttpURLConnection;importjava.net.MalformedURLException;importjava.net.URL;public classHttpUtils

{public staticInputStream getInputStream(String path)

{

InputStream inputStream= null;

HttpURLConnection httpURLConnection= null;try{

URL url= newURL(path);if (null !=url)

{

httpURLConnection=(HttpURLConnection) url.openConnection();//设置连接网络的超时时间

httpURLConnection.setConnectTimeout(5000);//打开输入流

httpURLConnection.setDoInput(true);//设置本次Http请求使用的方法

httpURLConnection.setRequestMethod("GET");if (200 ==httpURLConnection.getResponseCode())

{//从服务器获得一个输入流

inputStream =httpURLConnection.getInputStream();

}

}

}catch(MalformedURLException e)

{

e.printStackTrace();

}catch(IOException e)

{

e.printStackTrace();

}returninputStream;

}

}

另一个辅助类提供了方法,将位图存入SD卡的指定路径:

packagecom.windexample.utils;importjava.io.File;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.IOException;importandroid.graphics.Bitmap;importandroid.os.Environment;importandroid.util.Log;public classFileUtils

{private static String TAG = "File";public staticString getSDCardRootPath()

{//SD卡根目录

String sDCardRoot =Environment.getExternalStorageDirectory()

.getAbsolutePath();returnsDCardRoot;

}public static voidsaveToSDCard(Bitmap bitmap, String filePath,

String fileName)

{//将所给文件路径和文件名与SD卡路径连接起来

String sdcardRoot =getSDCardRootPath();//创建文件路径

File dir = new File(sdcardRoot + File.separator +filePath);

Log.i(TAG,"dir: " +dir);if (!dir.exists())

{

dir.mkdirs();

}

File targetFile= newFile(dir, fileName);try{

targetFile.createNewFile();

FileOutputStream fileOutputStream= newFileOutputStream(targetFile);

bitmap.compress(Bitmap.CompressFormat.JPEG,100, fileOutputStream);

fileOutputStream.flush();

fileOutputStream.close();

}catch(FileNotFoundException e)

{

e.printStackTrace();

}catch(IOException e)

{

e.printStackTrace();

}

}

}

程序运行后并得到图片后,结果如下:

b46e83563fec0a5c85ac9f549d577839.png

并且查看SD卡下的TestImage路径,发现其中有这个图片文件。

参考资料

Android Training: Connecting to the Network:

Android Training: Processes and Threads

老罗Android开发视频教程。

Android之网络编程 系列博文:

本博客前面博文中利用org.apache.http包中API进行Android客户端HTTP连接的例子:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值