HuTool

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpRequest;

*** 简单 get 请求
String jsonStr = HttpUtil.get(url);

*** 带参数, 带请求头 post
cn.hutool.json.JSONObject param = JSONUtil.createObj();
param.put("project_id", projectId);
param.put("project_name", projectName);

String resultJson = HttpRequest.post(getUrl)
        .header("token", token)
        .body(param)
        .execute().body();

*** get 获取图片
byte[] bytes = HttpRequest.get(getUrl)
        .header("token", token)
        .execute().bodyBytes();
FileOutputStream fos = new FileOutputStream("d:/mpl.jpg");
fos.write(bytes);
fos.close();

下载到固定位置, d 盘

注: 跟普通请求不一样的地方 , 在返回的是bodyBytes() , 开始返回的是String , 结果就乱码了, 返回的String 再转byte 也是行不通的, 因为获取前就乱码了

*** 获取图片, 二进制流输出
public String blockCallBack(HttpServletResponse response) throws Exception {
byte[] bytes = HttpRequest.get(getUrl)
        .header("Content-Type","application/octet-stream")
        .header("token", token)
        .header("content-disposition", "attachment;filename=" + URLEncoder.encode("test", "UTF-8"))
        .execute().bodyBytes();

OutputStream outputStream = response.getOutputStream();
outputStream.write(bytes);
outputStream.flush();
outputStream.close();
}

*** 还可以使用 HttpUtil工具类
//带参post
String result= HttpUtil.post("http://10.1.3.4:8030/api/inspection/uploadVideo", param);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章