春季:使用InputStreamResource发布请求

时间:2018-10-10 09:15:20

标签: spring spring-web

我有一些InputStream,并希望使用spring-web中的RestTempalte进行发布请求。

public void postRequest(InputStream in){
    MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<>();
    parameters.add("file", new InputStreamResource(inputStream) {
        @Override
        public String getFilename(){
            return "some_name";
        }
    });

    HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(parameters);

    restTemplate.postForEntity(SOME_ENDPOINT, httpEntity, String.class)
}

当我调用此方法时,发生IllegalStateException。

Exception in thread "main" java.lang.IllegalStateException: InputStream has already been read - do not use InputStreamResource if a stream needs to be read multiple times

在InputStreamResource的源代码getInputStream()方法中,我们可以看到:

public InputStream getInputStream() throws IOException, IllegalStateException {
    if (this.read) {
        throw new IllegalStateException("InputStream has already been read - " +
                "do not use InputStreamResource if a stream needs to be read multiple times");
    }
    this.read = true;
    return this.inputStream;
}

我该如何初始化InputStreamResource?我想念什么?

1 个答案:

答案 0 :(得分:3)

我通过重写getContentLenght()来解决它

# Somehow read assignation of df, 
# check that in global environment df is not presented and run
# tmp = df after next line is executed
df = pd.DataFrame({'a': [1, 2], 'b': [2, 3]})

# again parse following line,
# run tmp2=df after next line execution,
# compare tmp2 and tmp, write differences into log file
# assign tmp = tpm2 and wait for the next assignation occurance
df.loc[:, 'c'] = [3, 4]

因为本机方法public void postRequest(InputStream in){ MultiValueMap<String, Object> parameters = new LinkedMultiValueMap<>(); parameters.add("file", new InputStreamResource(inputStream) { @Override public String getFilename(){ return "some_name"; } @Override public long contentLength() throws IOException { return -1; } }); HttpEntity<MultiValueMap<String, Object>> httpEntity = new HttpEntity<>(parameters); restTemplate.postForEntity(SOME_ENDPOINT, httpEntity, String.class) } 调用contentLength()来计算长度。当第二次调用getInputStream()从流中获取内容时,我们会得到异常。