python requests 直接返回请求中文件

python requests 直接返回请求中文件

场景

  1. Java后台使用HttpClient调用Python flask
  2. python 使用requests 调用其他项目(请求中存在可下载的文件)
  3. python 使用flask将从其他项目中获取的文件返回给Java后台

JAVA代码

没什么特别的,不做额外说明


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.DateUtils;
import lombok.SneakyThrows;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Objects;

public class DownloadFile {

    @SneakyThrows
    public static void main(String[] args) {
        // 请求地址(python flask 地址:端口/路由)
        String url = "";
        // 创建请求对象并配置属性
        HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(url).openConnection();
        // 设置连接时间,10分钟
        httpURLConnection.setConnectTimeout(10 * 60 * 1000);
        httpURLConnection.setReadTimeout(10 * 60 * 1000);
        // 设置true,允许协议使用缓存
        httpURLConnection.setUseCaches(false);
        // request的请求方式
        httpURLConnection.setRequestMethod("GET");
        // 数据编码格式,这里utf-8
        httpURLConnection.setRequestProperty("Charset", "utf-8");
        // 设置返回结果的类型,这里是json
        httpURLConnection.setRequestProperty("accept", "application/json");
        // 设置请求类型为发送&下载
        httpURLConnection.setRequestProperty("Content-Type", "application/octet-stream");
        // 发送下载文件请求
        String result = getFileContent(httpURLConnection, "文件全路径+指定的文件名.文件后缀");
        // 请求结果转json
        JSONObject json = JSON.parseObject(result);
        if (Objects.nonNull(json) && Objects.equals(json.getString("code"), "200")) {
            // 获取已下载文件
            FileInputStream file = new FileInputStream("文件全路径+指定的文件名.文件后缀");
            // 以下解析文件并执行业务代码
            // .....
        }
    }

    public static String getFileContent(HttpURLConnection urlConnection, String filePath) {
        String result = null;
        try {
            // 开启客户端与Url所指向的资源的网络连接
            urlConnection.connect();
            //HTTP_OK 即200,连接成功的状态码
            if (200 == urlConnection.getResponseCode()) {
                if (urlConnection.getContentLength() > 0) {
                    byte[] file = input2byte(urlConnection.getInputStream());
                    writeBytesToFile(file, filePath);
                    JSONObject downloadFileResult = new JSONObject();
                    downloadFileResult.fluentPut("code", "200");
                    downloadFileResult.fluentPut("code_str", "下载成功");
                    downloadFileResult.fluentPut("file_path", filePath);
                    downloadFileResult.fluentPut("file_time", DateUtils.getTime());
                    return downloadFileResult.toJSONString();
                }
            } else {
                result = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            result = null;
        } finally {
            try {
                if (urlConnection != null) {
                    //解除连接,释放网络资源
                    urlConnection.disconnect();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static final byte[] input2byte(InputStream inStream)
            throws IOException {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inStream.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        byte[] in2b = swapStream.toByteArray();
        return in2b;
    }

    public static void writeBytesToFile(byte[] b, String outputFile) throws IOException {
        File file = null;
        FileOutputStream os = null;
        file = new File(outputFile);
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        if (!file.exists()) {
            file.createNewFile();
        }
        os = new FileOutputStream(file);
        os.write(b);
        if (os != null) {
            os.close();
        }
    }

}

Python 代码

import requests

from flask import (Flask,Response)
app = Flask(__name__)

@app.route("/testFile")
def test_file():
    # 发送下载请求
    get_file = requests.post(
        url="请求路径",
        data="入参",
        headers="请求头",
    )
    # 生成响应结果
    result = Response(content_type='application/octet-stream')
    result.status_code = get_file.status_code
    if 200 == get_file.status_code:
        # 将文件写入请求结果
        result.data = get_file.content
    else:
        result.data = "下载失败!"
    return result

你可能感兴趣的:(python,flask,开发语言,java,http)