JAVA 调用Open AI 接口生成图片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.浏览器访问展示效果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风清扬【coder】

请作者喝杯咖啡吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值