写点什么

JAVA 调用 Open AI 接口生成图片 url 并直接在浏览器上响应显示

作者:风清扬
  • 2023-11-03
    日本
  • 本文字数:2254 字

    阅读完需:约 7 分钟

JAVA 调用Open AI 接口生成图片url并直接在浏览器上响应显示

需求:chatGPT 作画生成图片,Java 调用 open ai 接口生成图片的 url,Java 在后台将图片的 url 转成流在浏览器直接展示。

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);
//可以为null // Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("127.0.0.1", 7890)); HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(new OpenAILogger()); //!!!!千万别再生产或者测试环境打开BODY级别日志!!!! //!!!生产或者测试环境建议设置为这三种级别:NONE,BASIC,HEADERS,!!! httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.NONE); OkHttpClient okHttpClient = new OkHttpClient .Builder()// .proxy(proxy) .addInterceptor(httpLoggingInterceptor) .addInterceptor(new OpenAiResponseInterceptor()) .connectTimeout(10, TimeUnit.SECONDS) .writeTimeout(30, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .build(); OpenAiClient v2 = OpenAiClient.builder() //支持多key传入,请求时候随机选择 .apiKey(Arrays.asList("sk-*********")) //自定义key的获取策略:默认KeyRandomStrategy //.keyStrategy(new KeyRandomStrategy())// .keyStrategy(new FirstKeyStrategy()) .okHttpClient(okHttpClient) //自己做了代理就传代理地址,没有可不不传,(关注公众号回复:openai ,获取免费的测试代理地址) .apiHost("https://*****.com/") .build();
ImageResponse imageResponse = v2.genImages(prompt); System.out.println(imageResponse);// Image image = Image.builder().prompt("电脑画面").responseFormat(ResponseFormat.B64_JSON.getName()).build();// ImageResponse imageResponse = v2.genImages(image);// 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 {   /**   *    * @description: 从服务器获得一个输入流(本例是指从服务器获得一个image输入流)   * @param urlPath   * @return   */  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;  }   /**   *    * @description: 将输入流输出到页面   * @param resp   * @param 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.浏览器访问展示效果


发布于: 刚刚阅读数: 3
用户头像

风清扬

关注

见自己,见世界,见众生 2020-07-01 加入

还未添加个人简介

评论

发布
暂无评论
JAVA 调用Open AI 接口生成图片url并直接在浏览器上响应显示_openai_风清扬_InfoQ写作社区