我有一个OkHttp请求:
public String createImageEditWithOkHttp(String prompt) throws IOException
{
OkHttpClient client = new OkHttpClient().newBuilder()
.connectTimeout(30, TimeUnit.SECONDS)
.callTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.build();
RequestBody body = new MultipartBody.Builder().setType(MultipartBody.FORM)
.addFormDataPart("image","file",
RequestBody.create(MediaType.parse("application/octet-stream"),
ResourceUtils.getFile("classpath:image_edit_original.png")))
.addFormDataPart("mask","file",
RequestBody.create(MediaType.parse("application/octet-stream"),
ResourceUtils.getFile("classpath:image_edit_mask.png")))
.addFormDataPart("prompt",prompt)
.addFormDataPart("n","1")
.addFormDataPart("size", ImageSize.SMALL.getSize())
.build();
Request request = new Request.Builder()
.url(IMAGE_EDIT_URL)
.method("POST", body)
.addHeader("Authorization", "Bearer " + OPENAI_API_KEY)
.build();
Response response = client.newCall(request).execute();
return response.body().string();
}
在这里,从资源中读取文件,并将其作为multipartfile与okhttp post请求一起发送。OkHttp版本的工作原理与预期相同。但当我尝试将其转换为resttemplate版本时,它无法在请求男孩上找到文件。
我想把它转换成spring resttemplate request:
public String createImageEditWithRestTemplate(String prompt) throws FileNotFoundException
{
HttpEntity<MultiValueMap<String, Object>> requestEntity
= new HttpEntity<>(createBody(prompt), commonHttpHeaders());
ResponseEntity<String> response = restTemplate.postForEntity(IMAGE_EDIT_URL, requestEntity, String.class);
return response.getBody();
}
private MultiValueMap<String, Object> createBody(String prompt) throws FileNotFoundException
{
MultiValueMap<String,Object> body = new LinkedMultiValueMap<>();
body.add("image", ResourceUtils.getFile("classpath:image_edit_original.png"));
body.add("mask", ResourceUtils.getFile("classpath:image_edit_mask.png"));
body.add("prompt",prompt);
body.add("n","1");
body.add("size", ImageSize.SMALL.getSize());
return body;
}
private HttpHeaders commonHttpHeaders()
{
MultiValueMap<String,String> headers = new LinkedMultiValueMap<>();
headers.add("Authorization", "Bearer " + OPENAI_API_KEY);
headers.add("Content-Type", org.springframework.http.MediaType.MULTIPART_FORM_DATA_VALUE);
return new HttpHeaders(headers);
}
但是在请求中找不到作为文件的图像。有什么建议吗?
2条答案
按热度按时间xxhby3vn1#
好的,我找到问题了。我们需要用
FileSystemResource
Package 器发送文件。voase2hg2#
你需要使用
Resource
而不是文件对象。当你从classpath阅读文件时,你可以使用ClassPathResource
。此外,你有方法来设置BearerAuth和Content-Type。如果你没有在
RestTemplate
中设置超时,那么使用httpclient
库并生成RestTemplate对象,如下所示。