《Java使用http协议将服务器图片下载到本地.docx》由会员分享,可在线阅读,更多相关《Java使用http协议将服务器图片下载到本地.docx(2页珍藏版)》请在三一办公上搜索。
1、Java使用http协议将服务器图片下载到本地JAVA使用http协议将服务器图片下载到本地 1 服务器端新建java web项目 该图片资源路径为 http:/localhost:8080/httppost/android.jpg 2 客服端 HttpUtils.java 代码如下: packagecom.zwh.http; importjava.io.FileOutputStream; importjava.io.IOException; importjava.io.InputStream; .HttpURLConnection; import .URL; publicclassHttpU
2、tils privatestatic String URL_PATH = http:/localhost:8080/httppost/android.jpg; publicHttpUtils / TODO Auto-generated constructor stub publicstaticvoidsaveToDisk / 获取输入流 InputStreaminputStream = getInputStream; byte date = newbyte1024; intlen = 0; FileOutputStreamfileOutputStream = null; try fileOut
3、putStream = newFileOutputStream(F:/example.jpg); while (len = inputStream.read(date) != -1) fileOutputStream.write(date, 0, len); catch (IOException e) / TODO Auto-generated catch block e.printStackTrace; finally try if (inputStream != null) inputStream.close; if (fileOutputStream != null) fileOutpu
4、tStream.close; catch (IOException e) / TODO Auto-generated catch block e.printStackTrace; /* * return */ publicstaticInputStreamgetInputStream InputStreaminputStream = null; HttpURLConnectionhttpURLConnection = null; try URL url = newURL(URL_PATH); httpURLConnection = (HttpURLConnection) url.openCon
5、nection; / 设置连接网络的超时时间 httpURLConnection.setConnectTimeout(3000); httpURLConnection.setDoInput(true); httpURLConnection.setRequestMethod(GET); intresponseCode = httpURLConnection.getResponseCode; if (responseCode = 200) inputStream = httpURLConnection.getInputStream; catch (Exception e) / TODO Auto-generated catch block e.printStackTrace; returninputStream; publicstaticvoidmain(String args) HttpUtilshttpUtils = newHttpUtils; httpUtils.saveToDisk;