• JAVA获取Get请求的InputStream,将InputStream写到本地文件中


    public class HttpTest {
    	public static void main(String[] args) throws IOException {
    		InputStream inputStream = getInputStream();
    		String path = "C:\Users\12449\Desktop\返回结果.txt";
    		writeToLocal(path,inputStream);
    		System.out.println();
    	}
    	
    	/**
    	 * 
    	 * @Title: getInputStream
    	 * @Description: TODO 获取网络连接的InputStream
    	 * @return
    	 * @throws IOException 
    	 * @CreateDate:2021 Nov 2 20:56:56
    	 */
    	public static InputStream getInputStream() throws IOException{
    		InputStream inputStream=null;
    		HttpURLConnection httpurlconn=null;
    		try {
    			URL url=new URL("path");
    			if(url!=null) {
    				httpurlconn=(HttpURLConnection) url.openConnection();
    				//设置连接超时时间
    				httpurlconn.setConnectTimeout(3000);
    				//表示使用GET方式请求
    				httpurlconn.setRequestMethod("GET");
    				httpurlconn.setRequestProperty("Authorization", "authorization");
    				int responsecode=httpurlconn.getResponseCode();
    				if(responsecode==200) {
    					//从服务返回一个输入流
    					inputStream=httpurlconn.getInputStream();
    				}
    			}
    		}catch (MalformedURLException e) {
    			e.printStackTrace();
    		}
    		return inputStream;
    	}
    	
    	/**
    	 * 将InputStream写入本地文件
    	 * @param destination 写入本地目录
    	 * @param input	输入流
    	 * @throws IOException
    	 */
    	private static void writeToLocal(String destination, InputStream input)
    			throws IOException {
    		int index;
    		byte[] bytes = new byte[1024];
    		FileOutputStream downloadFile = new FileOutputStream(destination);
    		while ((index = input.read(bytes)) != -1) {
    			downloadFile.write(bytes, 0, index);
    			downloadFile.flush();
    		}
    		downloadFile.close();
    		input.close();
    	}
    }
    

      

  • 相关阅读:
    实现单台测试机6万websocket长连接
    关于ArcGIS10.0中的栅格计算中的函数
    .NET破解之迅捷PDF转换器(续)
    ArcEngine 0x8004023C
    VS2010中重命名项目
    地理数据库本身不能加密
    ArcEngine尝试读取或写入受保护的内存
    利用路由器连接别人家的网络
    ArcGIS的许可文件问题
    MapGIS转Shp文件的单位问题
  • 原文地址:https://www.cnblogs.com/wwssgg/p/15501060.html
Copyright © 2020-2023  润新知