使用InputStream而不是Java文件发布多部分表单

时间:2019-11-07 06:59:25

标签: java httpclient multipart

我想将CSV格式的数据发布到外部URL。 URL需要包含字符串和文件的多部分形式。在我看来,这需要先将文件保存到磁盘,然后才能调用URL。是否可以在不将文件保存到磁盘的情况下使用此URL(这是美国人口普查局的地理编码服务)?例如,我可以使用仅临时存在于内存中的ByteArrayInputStream吗?下面是我的初始代码,其中涉及将文件保存到磁盘。

        String benchmark = "9";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost uploadFile = new HttpPost("https://geocoding.geo.census.gov/geocoder/locations/addressbatch");
        MultipartEntityBuilder builder2 = MultipartEntityBuilder.create();
        builder2.addTextBody("benchmark", benchmark, ContentType.TEXT_PLAIN);
        File f = new File("UscbGeocodingInput.csv");
        FileInputStream is = new FileInputStream(f);

        builder2.addBinaryBody(
                "addressFile",
                is,
                ContentType.APPLICATION_OCTET_STREAM,
                f.getName());

        HttpEntity multipart = builder2.build();
        uploadFile.setEntity(multipart);
        CloseableHttpResponse response = httpClient.execute(uploadFile);

我不想将文件保存到磁盘,因为在我们调用外部URL之前,它仅需要临时存在。我尝试使用字节数组输入流代替F ileInputStream,但请求随后以400 error失败。

2 个答案:

答案 0 :(得分:0)

  

我可以使用ByteArrayInputStream吗?

是的,但是当过载直接导致byte[]时,为什么要这样做呢?

addBinaryBody(String name, byte[] b, ContentType contentType, String filename)

答案 1 :(得分:0)

此方法有效...事实证明,美国人口普查局的地理编码API查找以“ .csv”结尾的文件名。即使我传递的是字节数组而不是文件,您仍然需要为该输入流命名。

        String benchmark = "9";
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost uploadFile = new HttpPost("https://geocoding.geo.census.gov/geocoder/locations/addressbatch");
        MultipartEntityBuilder builder2 = MultipartEntityBuilder.create();
        builder2.addTextBody("benchmark", benchmark, ContentType.TEXT_PLAIN);
        byte[] addressFileAsBytes = baos.toByteArray();
//      AnalyzeInputStream(is);

        builder2.addBinaryBody(
                "addressFile",
                addressFileAsBytes,
                ContentType.APPLICATION_OCTET_STREAM,
                "anyStringThatEndsInDotCSV.csv");
        HttpEntity multipart = builder2.build();
        uploadFile.setEntity(multipart);
        CloseableHttpResponse response = httpClient.execute(uploadFile);
        HttpEntity responseEntity = response.getEntity();