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