是的,在uniapp中调用图像识别API时,需要在Java代码中编写请求签名,以下是详细的步骤和示例代码:
(图片来源网络,侵删)1、需要导入相关的依赖库,如commonscodec
和commonsfileupload
,可以在项目的pom.xml
文件中添加以下依赖:
<dependencies> <dependency> <groupId>commonscodec</groupId> <artifactId>commonscodec</artifactId> <version>1.15</version> </dependency> <dependency> <groupId>commonsfileupload</groupId> <artifactId>commonsfileupload</artifactId> <version>1.4</version> </dependency> </dependencies>
2、创建一个方法来生成请求签名,这个方法需要接收三个参数:accessKeyId
(访问密钥ID),accessKeySecret
(访问密钥)和expires
(过期时间),返回值是一个字符串,表示生成的签名。
import org.apache.commons.codec.digest.HmacUtils; import java.nio.charset.StandardCharsets; import java.text.SimpleDateFormat; import java.util.Date; public String generateSignature(String accessKeyId, String accessKeySecret, int expires) { try { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd'T'HH:mm:ss"); String dateStr = sdf.format(new Date(System.currentTimeMillis() + expires * 1000)); String stringToSign = "GET&%2F&" + dateStr; byte[] signData = stringToSign.getBytes(StandardCharsets.UTF_8); byte[] keyData = accessKeySecret.getBytes(StandardCharsets.UTF_8); String signature = HmacUtils.hmacSha1Hex(keyData, signData); return "AWS4HMACSHA256 Credential=" + accessKeyId + "/" + dateStr + "/cnnorth1/image/v4/request, SignedHeaders=host, Signature=" + signature; } catch (Exception e) { e.printStackTrace(); return null; } }
3、在调用图像识别API时,将生成的签名添加到请求头中,使用HttpURLConnection
发送请求:
import java.net.HttpURLConnection; import java.net.URL; public void callImageRecognitionApi(String urlString, String accessKeyId, String accessKeySecret, int expires) { try { URL url = new URL(urlString); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Authorization", generateSignature(accessKeyId, accessKeySecret, expires)); connection.connect(); int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // 处理响应数据 } else { // 处理错误情况 } } catch (Exception e) { e.printStackTrace(); } }
4、调用callImageRecognitionApi
方法,传入图像识别API的URL、访问密钥ID、访问密钥和过期时间。
最新评论
本站CDN与莫名CDN同款、亚太CDN、速度还不错,值得推荐。
感谢推荐我们公司产品、有什么活动会第一时间公布!
我在用这类站群服务器、还可以. 用很多年了。