如何下载通过 Java 中的 HTTP 请求处理的文件?

How to download a file that gets processed over an HTTP request in Java?

我正在编写一个在 GUI 中构建内容的程序(blah blah blah ...不相关的细节),并且允许用户将该数据导出为可以编译为 PDF 的 .tex 文件。因为我真的不想假设他们安装了 TeX 环境,所以我使用的是 API (latexonline.cc)。这样,我可以构造一个 HTTP GET 请求,将其发送到 API,然后(希望!)return 字节流中的 PDF。但问题是,当我提交请求时,我只从请求中获取页面数据,而不是从 PDF 中获取数据。我不确定是不是因为我的请求方式...

代码如下:

... // preceding code
DataOutputStream dos = new DataOutputStream(new FileOutputStream("test.pdf"));
StringBuilder httpTex = new StringBuilder();
httpTex.append(this.getTexCode(...)); // This appends the TeX code (nothing wrong here)

// Build the URL and HTTP request.
String texURL = "https://latexonline.cc/compile?text=";
String paramURL = URLEncoder.encode(httpTex.toString(), "UTF-8");

URL url = new URL(texURL + paramURL);
byte[] buffer = new byte[1024];
try {
    InputStream is = url.openStream();
    int bufferLen = -1;
    while ((bufferLen = is.read(buffer)) > -1) {
        this.getOutputStream().write(buffer, 0, bufferLen);
    }

    dos.close();
    is.close();
} catch (IOException ex) {
    ex.printStackTrace();
}

编辑:这是我从 GET 请求中获取的数据: https://pastebin.com/qYtGXUsd

已解决!我使用了不同的 API 并且效果很好。

https://github.com/YtoTech/latex-on-http