zoukankan      html  css  js  c++  java
  • 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();
    	}
    }
    

      

  • 相关阅读:
    如何选出一支优秀的债券基金?
    来吧,今天说说股票型基金
    来吧,帮你认识基金
    债券基金有A、有B、还有C,到底买哪种?
    基金到底分几类
    来吧,一个指标让你选到优秀的“固收+"基金
    来吧,带你读懂债券基金
    Windows 彻底删除文件
    IntelliJ IDEA 工程、模块常用操作
    IntelliJ IDEA 创建项目(开发第一个程序)
  • 原文地址:https://www.cnblogs.com/wwssgg/p/15501060.html
Copyright © 2011-2022 走看看