1.添加JAVA调用Open AI 的依赖
<dependency>
<groupId>com.unfbx</groupId>
<artifactId>chatgpt-java</artifactId>
<version>1.0.14-beta1</version>
</dependency>
2.编写生成图片的controller接口
@GetMapping("createImage")
public void createImage(String prompt, HttpServletRequest request, HttpServletResponse response) {
System.out.println("prompt=" + prompt);
HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new OpenAILogger());
httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.NONE);
OkHttpClient okHttpClient = new OkHttpClient
.Builder()
.addInterceptor(httpLoggingInterceptor)
.addInterceptor(new OpenAiResponseInterceptor())
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.build();
OpenAiClient v2 = OpenAiClient.builder()
.apiKey(Arrays.asList("sk-*********"))
.okHttpClient(okHttpClient)
.apiHost("https://*****.com/")
.build();
ImageResponse imageResponse = v2.genImages(prompt);
System.out.println(imageResponse);
List<Item> items = imageResponse.getData();
String urlPath = items.get(0).getUrl();
InputStream inputStream = HttpUtils.getInputStream(urlPath);
HttpUtils.writeFile(response, inputStream);
}
3.编写HttpUtils工具类
package com.jeff.utils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import javax.servlet.http.HttpServletResponse;
public class HttpUtils {
public static InputStream getInputStream(String urlPath) {
InputStream inputStream = null;
HttpURLConnection httpURLConnection = null;
try {
URL url = new URL(urlPath);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setConnectTimeout(3000);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestMethod("GET");
int responseCode = httpURLConnection.getResponseCode();
System.out.println("responseCode is:" + responseCode);
if (responseCode == HttpURLConnection.HTTP_OK) {
inputStream = httpURLConnection.getInputStream();
} else {
inputStream = httpURLConnection.getErrorStream();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return inputStream;
}
public static void writeFile(HttpServletResponse resp, InputStream inputStream) {
resp.setContentType("image/jpeg");
OutputStream out = null;
try {
out = resp.getOutputStream();
int len = 0;
byte[] b = new byte[1024];
while ((len = inputStream.read(b)) != -1) {
out.write(b, 0, len);
}
out.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
4.浏览器访问展示效果
