http协议GET方式获取图片
2014-02-16 22:06
344 查看
package com.http.get; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; public class HttpUtils { // 自定义的web服务器的资源 private static String URL_PATH = "http://172.16.47.156:8080/myhttp/2.jpg"; public HttpUtils() { // TODO Auto-generated constructor stub } public static void saveImageToDisk() throws IOException { InputStream inputStream = getInputStream(); byte[] data = new byte[1024]; int len = 0; FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream("D:\\Temp\\testhttp.jpg"); while ((len = inputStream.read(data)) != -1) { fileOutputStream.write(data, 0, len); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { if (inputStream != null) { try { inputStream.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (fileOutputStream != null) { try { fileOutputStream.close(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } /** * 获得服务器端数据,以InputStream形式返回 * * @return * @throws IOException */ public static InputStream getInputStream() throws IOException { InputStream inputStream = null; HttpURLConnection httpURLConnection = null; try { URL url = new URL(URL_PATH); if (url != null) { httpURLConnection = (HttpURLConnection) url.openConnection(); // 设置连接网络的超时时间 httpURLConnection.setConnectTimeout(3000); httpURLConnection.setDoInput(true); // 设置本次http请求使用get方式请求 httpURLConnection.setRequestMethod("GET"); int responseCode = httpURLConnection.getResponseCode(); if (responseCode == 200) { // 从服务器获得一个输入流 inputStream = httpURLConnection.getInputStream(); } } } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return inputStream; } public static void main(String[] args) throws IOException { // 从服务器获得图片保存到本地 saveImageToDisk(); System.out.println("传输步骤完毕"); } }
来源:http://blog.csdn.net/ysl296/article/details/14434655
相关文章推荐
- Http协议获取图片数据流(GET方式)
- http协议get方式从服务器获取图片并保存到本地
- http协议get方式获取图片
- http编程系列2:http协议GET方式获取网络图片
- 使用httpget方式获取网络上的图片
- Android HttpURLConnection(Get,Post方式)进行网络通信 获取数据和网络图片
- 通过Http协议以Get和Post方式获取服务器端文本数据
- http协议4---GET方式和POST方式获取表单数据举例3(统一方式获取,解决中文乱码问题)
- http协议3---GET方式和POST方式获取表单数据举例2(统一方式获取)
- http协议2---GET方式和POST方式获取表单数据举例 1(非统一方式获取数据,比较麻烦)
- HTTP协议传输中GET方式与POST方式区别
- 学习笔记分享(1),Http协议中Post方式与Get方式的传参形式
- ym——Android从零开始(16)(HTTP协议请求、获取图片、json数据)(新)
- http协议中的几种请求的方式(Get、Post、Put、Head、Delete、Options、Trace和Connect)
- 20170330_请说出HTTP 的两种协议GET 方式和POST 方式的区别
- .NET获取聚合数据接口数据(Http协议POST和GET请求)
- Unity3D 网络通信_HTTP协议:获取网络图片、内容
- 【Android】使用http的Post和Get方式获取网络数据
- C#中如何通过HTTP协议的不同请求方式获取数据
- 学习笔记分享(1),Http协议中Post方式与Get方式的传参形式