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();
    	}
    }
    

      

  • 相关阅读:
    文件高级应用和函数基础
    字符编码,文件操作
    数据类型分类,深浅拷贝
    容器数据类型内置方法
    数字类型和字符串类型内置方法
    流程控制循环
    python 运算和流程控制
    【MySQL】SQL教程
    【MySQL】数据库字段类型
    【java】HashSet
  • 原文地址:https://www.cnblogs.com/wwssgg/p/15501060.html
Copyright © 2011-2022 走看看