在Java中访问第三方接口并接收返回的文件,可以通过使用HttpClient库来实现。下面是一个简单的示例代码:

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class Main {
    public static void main(String[] args) {
        HttpClient httpClient = HttpClientBuilder.create().build();
        HttpGet httpGet = new HttpGet("http://example.com/api/file");

        try {
            HttpResponse response = httpClient.execute(httpGet);
            HttpEntity entity = response.getEntity();

            if (entity != null) {
                InputStream inputStream = entity.getContent();
                // 保存文件到本地
                saveFile(inputStream, "output.txt");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void saveFile(InputStream inputStream, String filePath) throws IOException {
        OutputStream outputStream = new FileOutputStream(filePath);
        byte[] buffer = new byte[1024];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        outputStream.close();
        inputStream.close();
    }
}

在上面的示例代码中,我们使用HttpClient库发送一个GET请求到第三方接口,接收返回的文件。如果请求成功,我们会获取到返回的HttpEntity对象,然后从中获取到InputStream,最后将InputStream中的数据写入到本地文件中。请注意替换示例代码中的URL和文件名,以适应你的实际需求

java访问第三方接口返回一个文件如何接收

原文地址: http://www.cveoy.top/t/topic/iTkU 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录