it编程 > 网页制作 > 网页播放器

调用hutool包调用http接口处理文件流-文件的上传下载工具类

278人参与 2024-08-02 网页播放器

hutool工具类get请求获取流:
inputstream inputstream = httprequest.get(fileurl).execute().bodystream();

hutool工具类post请求上传文件流:
string resp = httprequest.post(url).header(header.content_type.getvalue(), contenttype.multipart.getvalue()).form(params).execute().body();

完成代码



import cn.hutool.core.io.resource.inputstreamresource;
import cn.hutool.http.contenttype;
import cn.hutool.http.header;
import cn.hutool.http.httprequest;
import cn.hutool.json.jsonarray;
import cn.hutool.json.jsonobject;
import cn.hutool.json.jsonutil;
import com.alibaba.fastjson.json;

import lombok.extern.slf4j.slf4j;
import org.apache.http.httpentity;
import org.apache.http.httpresponse;
import org.apache.http.namevaluepair;
import org.apache.http.client.httpclient;
import org.apache.http.client.config.requestconfig;
import org.apache.http.client.methods.httpget;
import org.apache.http.client.methods.httppost;
import org.apache.http.client.utils.uribuilder;
import org.apache.http.entity.stringentity;
import org.apache.http.impl.client.httpclientbuilder;
import org.apache.http.impl.client.httpclients;
import org.apache.http.util.entityutils;
import org.springframework.stereotype.service;
import org.springframework.web.context.request.requestcontextholder;
import org.springframework.web.context.request.servletrequestattributes;
import org.springframework.web.multipart.multipartfile;

import javax.servlet.http.httpservletrequest;
import java.io.*;
import java.net.uri;
import java.nio.charset.charset;
import java.util.*;

import java.io.ioexception;

@slf4j
@service
public class httputils {


    public int success_code = 200;
    public int filed_code = 500;


    public static string getcurrenttoken() {
        httpservletrequest request = ((servletrequestattributes) requestcontextholder.getrequestattributes())
                .getrequest();
//        string token = request.getheader("token");
        loginuserbo principal = (loginuserbo) securityutils.getauthentication().getprincipal();
        string token = principal.gettoken();
        return token;
    }


    /**
     * 有参post请求
     */
    public <t> string doposttestbyparam(string url, t t) {

        // 请求地址
//        string url = "http://localhost:8889/consumer/post";
        // post请求
        httpclient httpclient = null;
        httppost postmethod = null;
        httpresponse response = null;
        string responsecontent = null;
        try {
            // 获取http客户端
            httpclient = httpclients.createdefault();
            postmethod = new httppost(url);
            // 自定义对象
//            user user = new user();
            // 设置请求头
            postmethod.addheader("content-type", "application/json;charset=utf8");
            // 封装请求体
            postmethod
                    .setentity(new stringentity(json.tojsonstring(t), charset.forname("utf-8")));
            // 发送请求
            response = httpclient.execute(postmethod);
            // 获取响应结果
            int statuscode = response.getstatusline().getstatuscode();
            // 响应对象
            httpentity httpentity = response.getentity();
            // 响应的字符串
            responsecontent = entityutils.tostring(httpentity, "utf-8");
            //释放资源
            entityutils.consume(httpentity);
            return responsecontent;
        } catch (ioexception e) {
            log.info("请求异常, 错误信息为: {} ", e.getmessage());
            return null;
        }
    }


    /**
     * 有参get请求 添加请求配置
     * params.add(new basicnamevaluepair("key", "123456"));
     * params.add(new basicnamevaluepair("id", "123123"));
     * list<namevaluepair> params = new arraylist<>();
     */
    public static httpresponse dogettestbyuri(list<namevaluepair> params, string scheme, string host, int port, string path) {
//        string url = "http://localhost:8889/consumer/get";
//        string currenttoken = getcurrenttoken();
        //  获取httpclient客户端
        httpclient httpclient = httpclientbuilder.create().build();
        //  发送请求
        httpresponse httpresponse = null;
        uri uri = null;
        try {
            uri = new uribuilder()
                    .setscheme(scheme)
                    .sethost(host)
                    .setport(port)
                    .setpath(path)
                    .setparameters(params)
                    .build();
            //  创建post请求
            httpget httppost = new httpget(uri);
//            httppost.setheader("authorization", "bearer " + currenttoken);
            httpresponse = httpclient.execute(httppost);

            // 配置请求信息
            requestconfig requestconfig = requestconfig.custom()
                    .setconnecttimeout(5000) // 连接超时时间
                    .setconnectionrequesttimeout(5000) //请求超时时间
                    .setsockettimeout(5000) // 读写超时时间
                    .setredirectsenabled(true) // 是否重定向 默认true开启
                    .build();
            httppost.setconfig(requestconfig);

            // 4 响应状态码 响应信息
            int statuscode = httpresponse.getstatusline().getstatuscode();
            log.info("响应状态码为: {} ", statuscode);

            // 响应信息
            httpentity httpentity = httpresponse.getentity();
            log.info("响应内容为: {} ", entityutils.tostring(httpentity));

            //释放资源
            entityutils.consume(httpentity);
            return httpresponse;
        } catch (exception e) {
            log.info("请求异常, 错误信息为: {} ", e.getmessage());
            return httpresponse;
        }

    }


    /**
     * 上传文件服务器
     *
     * @param file
     * @return
     */
    public jsonarray uploadfileservice(multipartfile file, string url) {
        map<string, object> params = new hashmap<>();
        jsonarray jsonarray = new jsonarray();
        params.put("files", createis(file));
        string resp = httprequest.post(url).header(header.content_type.getvalue(), contenttype.multipart.getvalue()).form(params).execute().body();
        log.info("fileserverresp:{}", resp);
        jsonobject respjson = jsonutil.parseobj(resp);
        string fileid = "";
        if (success_code == respjson.getint("code") && !respjson.getjsonarray("data").isempty()) {
            jsonarray = respjson.getjsonarray("data");
        }
        return jsonarray;
    }


    /**
     * 文件流转换
     *
     * @param file
     * @return
     */
    public inputstreamresource createis(multipartfile file) {
        inputstreamresource isr = null;
        try {
            isr = new inputstreamresource(file.getinputstream(), file.getoriginalfilename());
        } catch (ioexception e) {
            log.info("文件流转换异常:{}", e);
        }
        return isr;
    }


    public  inputstream downloadfile(string fileurl) throws ioexception {
        inputstream inputstream = null;
        try {
            inputstream = httprequest.get(fileurl).execute().bodystream();
            system.out.println("文件下载完成");
        } catch (exception e) {
            e.printstacktrace();
        }
        return inputstream;
    }


}








(0)
打赏 微信扫一扫 微信扫一扫

您想发表意见!!点此发布评论

推荐阅读

html—meta标签中的http-equiv属性

08-02

Django视图-HttpRequest请求对象和HttpResponse响应对象

08-02

【HTML——3d粒子特效(效果+代码)】

08-02

一个开源的AT命令解析模块

08-02

linux 运行开源音视频livekit,实现html视频语音聊天。

08-02

【CSS】记录一个简单的使用css animation完成警告灯闪烁效果

08-02

猜你喜欢

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论