将OkHttp请求转换为Spring RestTemplate请求

idfiyjo8  于 2023-04-11  发布在  Spring
关注(0)|答案(2)|浏览(231)

我有一个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);
}

但是在请求中找不到作为文件的图像。有什么建议吗?

xxhby3vn

xxhby3vn1#

好的,我找到问题了。我们需要用FileSystemResource Package 器发送文件。

private MultiValueMap<String, Object> createBody(String prompt) throws FileNotFoundException
{
    MultiValueMap<String,Object> body = new LinkedMultiValueMap<>();

    body.add("image", new FileSystemResource(ResourceUtils.getFile("classpath:image_edit_original.png")));
    body.add("mask", new FileSystemResource(ResourceUtils.getFile("classpath:image_edit_mask.png")));
    body.add("prompt",prompt);
    body.add("n","1");
    body.add("size", ImageSize.SMALL.getSize());

    return body;
}
voase2hg

voase2hg2#

你需要使用Resource而不是文件对象。当你从classpath阅读文件时,你可以使用ClassPathResource。此外,你有方法来设置BearerAuth和Content-Type。

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", new ClassPathResource("image_edit_original.png"));
    body.add("mask", new ClassPathResource("image_edit_mask.png"));
    body.add("prompt", prompt);
    body.add("n", "1");
    body.add("size", ImageSize.SMALL.getSize());
    return body;
}

private HttpHeaders commonHttpHeaders() {
    HttpHeaders headers = new HttpHeaders();
    headers.setBearerAuth(OPENAI_API_KEY);
    headers.setContentType(MediaType.MULTIPART_FORM_DATA);
    return headers;
}

如果你没有在RestTemplate中设置超时,那么使用httpclient库并生成RestTemplate对象,如下所示。

public RestTemplate getRestTemplate() throws KeyManagementException, NoSuchAlgorithmException {
    SSLContext sslContext = SSLContexts.custom().build();
    SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext);
    CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).useSystemProperties().build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setHttpClient(httpClient);
    requestFactory.setConnectTimeout(30000);
    requestFactory.setReadTimeout(30000);
    requestFactory.setConnectionRequestTimeout(30000);
    return new RestTemplate(requestFactory);
}

相关问题