当前位置: 首页 > news >正文

用url类来访问服务器上的文件

场景一:
package com.guonian.miaosha;import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;public class Test {public static void main(String[] args) throws IOException {URL url = new URL("http://192.168.1.220:8080/file/%FL%AC%94%E8%BA%.txt");//创建接口地址对象HttpURLConnection connection = (HttpURLConnection)url.openConnection();//设置请求方式//connection.setRequestMethod("GET");connection.connect();BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));String line = null;while(null != (line = br.readLine())){System.out.println(line);}br.close();}
}
场景2:
public static String image2Base64(String imgUrl, String token) {URL url;InputStream is = null;ByteArrayOutputStream outStream = null;HttpURLConnection httpUrl = null;try {url = new URL(imgUrl);httpUrl = (HttpURLConnection) url.openConnection();httpUrl.setDoOutput(true);httpUrl.setRequestMethod("GET");httpUrl.setRequestProperty("Authorization", token);httpUrl.connect();httpUrl.getInputStream();is = httpUrl.getInputStream();outStream = new ByteArrayOutputStream();//创建一个Buffer字符串byte[] buffer = new byte[1024];//每次读取的字符串长度,如果为-1,代表全部读取完毕int len = 0;//使用一个输入流从buffer里把数据读取出来while ((len = is.read(buffer)) != -1) {//用输出流往buffer里写入数据,中间参数代表从哪个位置开始读,len代表读取的长度outStream.write(buffer, 0, len);}// 对字节数组Base64编码return CommonUtils.encode(outStream.toByteArray());} catch (Exception e) {log.error("异常信息:", e);} finally {try {if (is != null) {is.close();}if (outStream != null) {outStream.close();}} catch (IOException e) {log.error("异常信息:", e);}if (httpUrl != null) {httpUrl.disconnect();}}return "";}
http://www.lryc.cn/news/185935.html

相关文章:

  • 【重拾C语言】六、批量数据组织(二)线性表——分类与检索(主元排序、冒泡排序、插入排序、顺序检索、对半检索)
  • 24 Python的sqlite3模块
  • ARM-流水灯
  • 【虚拟机】NAT 模式下访问外网
  • React 入门笔记
  • Ubuntu MySQL
  • 大数据软件系统开发框架
  • rust变量
  • 蓝桥杯---第一讲 递归与递推
  • OpenCV 15(SIFT/SURF算法)
  • 前端二维码图片解析图片识别/网络图片解析成链接/图片网络链接转本地链接(Js/Vue/Jquery)
  • 模板中的依赖类型使用 --- typename
  • git 同时配置 gitee github
  • 2023.10.8 面试
  • 【前端】js实现队列功能 先进后出 先进先出 等
  • 07.数据持久化之文件操作
  • nginx开启https配置之后网页无法访问问题处理
  • 文本嵌入层
  • 如何搭建自动化测试框架
  • 抄写Linux源码(Day17:你的键盘是什么时候生效的?)
  • 在原生html中使用less
  • 【Qt】顶层窗口和普通窗口区别以及用法
  • qt开发从入门到实战2
  • Android---字节码层面分析Class类文件
  • 【2023研电赛】东北赛区一等奖作品:基于FPGA的小型水下无线光通信端机设计
  • JWT授权为啥要在 Authorization标头里加个Bearer 呢
  • 一篇理解TCP协议
  • rk平台android12系统设置里面互联网选项中的以太网选项点击不了问题
  • ctrl+d和ctrl+c的区别
  • ChatGLM2-6B微调实践