httpmodel java_java使用HttpURLConnection接口调用ModelArts推理服务Demo

1.准备 iam_token.json

包含内容如下,其中name,pasword,domain name填写自己账户的配置,scope->project->name填写你所使用的region,这里以上海一为例,如果是北京四改成cn-north4

{

"auth": {

"identity": {

"methods": ["password"],

"password": {

"user": {

"name": "",

"password": "",

"domain": {

"name": ""

}

}

}

},

"scope": {

"project": {

"name": "cn-east-3"

}

}

}

}

2.准备input.json文件,文件中包含了你服务请求的内容

3.准备HttpURLConnectionUtil.java此文件是程序入口;三个文件放到一起就可以运行

注意:

1)其中postData()方法的第一个入参要设置成你自己的服务地址

A0ieDTtINtBSAAAAAElFTkSuQmCC

2)代码一共分两部分,第一部分是获取token,第二部分是调用推理请求。获取token的代码每12个小时更新一次就可以,不能频繁的调用,如果每次推理请求都调用一次token的更新,会导致获取token请求被拒绝。

w8UYhy6c2hSDQAAAABJRU5ErkJggg==

实际代码如下

import java.io.BufferedReader;

import java.io.IOException;

import java.io.InputStream;

import java.io.InputStreamReader;

import java.io.OutputStream;

import java.net.HttpURLConnection;

import java.net.MalformedURLException;

import java.net.URL;

import java.nio.charset.StandardCharsets;

import java.nio.file.Files;

import java.nio.file.Paths;

import java.io.*;

import java.net.URLConnection;

import java.util.List;

import java.util.Map;

public class HttpURLConnectionUtil {

public static String doGet(String httpurl) {

HttpURLConnection connection = null;

InputStream is = null;

BufferedReader br = null;

String result = null;// 返回结果字符串

try {

// 创建远程url连接对象

URL url = new URL(httpurl);

// 通过远程url连接对象打开一个连接,强转成httpURLConnection类

connection = (HttpURLConnection) url.openConnection();

// 设置连接方式:get

connection.setRequestMethod("GET");

// 设置连接主机服务器的超时时间:15000毫秒

connection.setConnectTimeout(15000);

// 设置读取远程返回的数据时间:60000毫秒

connection.setReadTimeout(60000);

// 发送请求

connection.connect();

// 通过connection连接,获取输入流

if (connection.getResponseCode() == 200) {

is = connection.getInputStream();

// 封装输入流is,并指定字符集

br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

// 存放数据

StringBuffer sbf = new StringBuffer();

String temp = null;

while ((temp = br.readLine()) != null) {

sbf.append(temp);

sbf.append("\r\n");

}

result = sbf.toString();

}

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

// 关闭资源

if (null != br) {

try {

br.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if (null != is) {

try {

is.close();

} catch (IOException e) {

e.printStackTrace();

}

}

connection.disconnect();// 关闭远程连接

}

return result;

}

public static String parseResponse(InputStream in) throws IOException

{

InputStreamReader inputStream = new InputStreamReader(in, "UTF-8" );

BufferedReader buff = new BufferedReader(inputStream);

StringBuilder sb = new StringBuilder();

String line = buff.readLine();

while (line != null )

{

sb.append(line);

line = buff.readLine();

}

return sb.toString();

}

public static String getToken(String httpUrl, String param) throws IOException {

HttpURLConnection connection = null;

InputStream is = null;

OutputStream os = null;

BufferedReader br = null;

String result = null;

try {

URL url = new URL(httpUrl);

// 通过远程url连接对象打开连接

connection = (HttpURLConnection) url.openConnection();

// 设置连接请求方式

connection.setRequestMethod("POST");

// 设置连接主机服务器超时时间:15000毫秒

connection.setConnectTimeout(15000);

// 设置读取主机服务器返回数据超时时间:60000毫秒

connection.setReadTimeout(60000);

// 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true

connection.setDoOutput(true);

// 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无

connection.setDoInput(true);

// 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。

connection.setRequestProperty("Content-Type", "application/json;charset=utf8");

// 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0

//connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");

// 通过连接对象获取一个输出流

os = connection.getOutputStream();

// 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的

os.write(param.getBytes());

os.flush();

//System.out.println(connection.getResponseCode());

String responseContent = parseResponse(connection.getInputStream());

Map> map = connection.getHeaderFields();

for (Map.Entry> entry : map.entrySet()) {

//System.out.println("Key : " + entry.getKey() + " ,Value : " + entry.getValue());

if (entry.getKey() != null && entry.getKey().equals("X-Subject-Token")) {

//System.out.println(entry.getValue());

result = entry.getValue().get(0);

}

}

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

// 关闭资源

if (null != br) {

try {

br.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if (null != os) {

try {

os.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if (null != is) {

try {

is.close();

} catch (IOException e) {

e.printStackTrace();

}

}

// 断开与远程地址url的连接

connection.disconnect();

}

return result;

}

public static String postData(String httpUrl, String param, String tokenStr) throws IOException {

HttpURLConnection connection = null;

InputStream is = null;

OutputStream os = null;

BufferedReader br = null;

String result = null;

try {

URL url = new URL(httpUrl);

// 通过远程url连接对象打开连接

connection = (HttpURLConnection) url.openConnection();

// 设置连接请求方式

connection.setRequestMethod("POST");

// 设置连接主机服务器超时时间:15000毫秒

connection.setConnectTimeout(15000);

// 设置读取主机服务器返回数据超时时间:60000毫秒

connection.setReadTimeout(60000);

// 默认值为:false,当向远程服务器传送数据/写数据时,需要设置为true

connection.setDoOutput(true);

// 默认值为:true,当前向远程服务读取数据时,设置为true,该参数可有可无

connection.setDoInput(true);

// 设置传入参数的格式:请求参数应该是 name1=value1&name2=value2 的形式。

connection.setRequestProperty("Content-Type", "application/json;charset=utf8");

connection.setRequestProperty("X-Auth-Token", tokenStr);

// 设置鉴权信息:Authorization: Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0

//connection.setRequestProperty("Authorization", "Bearer da3efcbf-0845-4fe3-8aba-ee040be542c0");

// 通过连接对象获取一个输出流

os = connection.getOutputStream();

// 通过输出流对象将参数写出去/传输出去,它是通过字节数组写出的

os.write(param.getBytes());

os.flush();

//System.out.println(connection.getResponseCode());

result = parseResponse(connection.getInputStream());

} catch (MalformedURLException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

} finally {

// 关闭资源

if (null != br) {

try {

br.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if (null != os) {

try {

os.close();

} catch (IOException e) {

e.printStackTrace();

}

}

if (null != is) {

try {

is.close();

} catch (IOException e) {

e.printStackTrace();

}

}

// 断开与远程地址url的连接

connection.disconnect();

}

return result;

}

public static void main(String[] args) throws IOException {

String tokenContent = new String(Files.readAllBytes(Paths.get("iam_token.json")), StandardCharsets.UTF_8);

//System.out.println(content);

String tokenStr = getToken("https://iam.cn-east-3.myhuaweicloud.com/v3/auth/tokens", tokenContent);

//System.out.println(tokenStr);

String requstData = new String(Files.readAllBytes(Paths.get("input.json")), StandardCharsets.UTF_8);

String message = postData("https://xxx.apig.cn-east-3.huaweicloudapis.com/v1/infers/xxx/xxxxx", requstData, tokenStr);

System.out.println(message);

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值