如何使用java调用Dalle3并返回字符串URL?

问题描述 投票:0回答:1

我的代码是这样的!但这是行不通的。该错误表示该模型不存在。但我尝试了很多模型。有谁知道吗

导入okhttp3.*;

导入java.io.IOException;

公共类 OpenAIDALL_EClient {

private static final String OPENAI_API_KEY = "your_openai_api_key";
private static final String OPENAI_API_ENDPOINT = "https://api.openai.com/v1/completions";

public static void main(String[] args) {
    String prompt = "generate a little robot";

    String imageUrl = callOpenAIDALL_EAndReturnImage(prompt);
    System.out.println("Image URL: " + imageUrl);
}

private static String callOpenAIDALL_EAndReturnImage(String prompt) {
    OkHttpClient client = new OkHttpClient();

    String json = "{\"model\":\"dall-e-003\", \"prompt\":\"" + prompt + "\", \"max_tokens\":50}";
    RequestBody requestBody = RequestBody.create(json, MediaType.parse("application/json"));

    Request request = new Request.Builder()
            .url(OPENAI_API_ENDPOINT)
            .header("Content-Type", "application/json")
            .header("Authorization", "Bearer " + OPENAI_API_KEY)
            .post(requestBody)
            .build();

    try {
        Response response = client.newCall(request).execute();
        if (response.isSuccessful()) {
            String responseBody = response.body().string();
            return responseBody;
        } else {
            System.out.println("OpenAI API request failed with response: " + response.body().string());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

}

我的代码是这样的!但这是行不通的。该错误表示该模型不存在。但我尝试了很多模型。有谁知道吗

java
1个回答
0
投票

您对 RequestBody.create 方法使用了不正确的语法。应该是这个 RequestBody.create(MediaType contectType, String content)

所以只需更改以下行

RequestBody requestBody = RequestBody.create(MediaType.parse("application/json"),json);

© www.soinside.com 2019 - 2024. All rights reserved.