调用图灵API

private static final String URL = "http://www.tuling123.com/openapi/api";
private static final String API_KEY = " ";//申请一个API_KEY

public static String doGet(String msg)

{
String result = "";
String url = setParams(msg);
ByteArrayOutputStream baos = null;
InputStream is = null;
try
{
java.net.URL urlNet = new java.net.URL(url);
HttpURLConnection conn = (HttpURLConnection) urlNet
.openConnection();//打开连接
conn.setReadTimeout(5 * 1000);
conn.setConnectTimeout(5 * 1000);
conn.setRequestMethod("GET");//设置为GET方式请求
is = conn.getInputStream();
int len = -1;
byte[] buf = new byte[128];
baos = new ByteArrayOutputStream();


while ((len = is.read(buf)) != -1)
{
baos.write(buf, 0, len);
}
baos.flush();
result = new String(baos.toByteArray());
} catch (MalformedURLException e)
{
e.printStackTrace();
} catch (Exception e)
{
e.printStackTrace();
} finally
{
try
{
if (baos != null)
baos.close();
} catch (IOException e)
{
e.printStackTrace();
}


try
{
if (is != null)
{
is.close();
}
} catch (IOException e)
{
e.printStackTrace();
}
}
return result;
}


private static String setParams(String msg)
{
String url = "";
try
{
url = URL + "?key=" + API_KEY + "&info="
+ URLEncoder.encode(msg, "UTF-8");
} catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
return url;
}


}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 引入相关依赖库 在项目的gradle中引入okhttp3和gson的依赖库: ```java dependencies { implementation 'com.squareup.okhttp3:okhttp:3.12.1' implementation 'com.google.code.gson:gson:2.8.5' } ``` 2. 定义接口 定义一个接口类RestApi接收回调 ```java public interface RestApi { void success(ChatResponse response); void failure(Exception e); } ``` 3. 准备提交的数据 首先我们要把urlapiKey作为成员变量定义出来: ```java private static final String BASE_URL = "http://openapi.tuling123.com/openapi/api/v2"; private static final String API_KEY = "*************************"; ``` 接着我们需要定义一个请求的实体类RequestBody,该实体类中包含了请求的参数信息,其中reqType表示请求的方式为0,输入文本类型的请求信息为1,即输入文本。 ```java class RequestBody { private Perception perception; private UserInfo userInfo; public RequestBody(Perception perception, UserInfo userInfo) { this.perception = perception; this.userInfo = userInfo; } static class Perception { private InputText inputText; public Perception(InputText inputText) { this.inputText = inputText; } static class InputText { private String text; public InputText(String text) { this.text = text; } } } static class UserInfo { private String apiKey; private String userId; public UserInfo(String apiKey, String userId) { this.apiKey = apiKey; this.userId = userId; } } } ``` 4. 发送请求到服务器 使用 OkHttp3 发送 POST 请求到服务器,并通过 JSON 格式将 RequestBody 对象以字符串的形式传递给服务器: ```java public void sendRequest(String msg, final RestApi api) { // 请求实体类封装 RequestBody.RequestBodyPerception.RequestBodyInputText inputText = new RequestBody.RequestBodyPerception.RequestBodyInputText(msg); RequestBody.RequestBodyPerception perception = new RequestBody.RequestBodyPerception(inputText); RequestBody.UserInfo userInfo = new RequestBody.UserInfo(API_KEY, "123456"); RequestBody requestBody = new RequestBody(perception, userInfo); // 将 requestbody 转成 json 格式 Gson gson = new Gson(); String json = gson.toJson(requestBody); // 创建请求 Request request = new Request.Builder() .url(BASE_URL) .post(RequestBody.create(MediaType.parse("application/json"), json)) .build(); // 发送请求 OkHttpClient okHttpClient = new OkHttpClient(); Call call = okHttpClient.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { api.failure(e); } @Override public void onResponse(Call call, Response response) throws IOException { try { Gson gson = new Gson(); ChatResponse chatResponse = gson.fromJson(response.body().string(), ChatResponse.class); api.success(chatResponse); } catch (Exception e) { api.failure(e); } } }); } ``` 5. 处理响应数据 在成功回调函数中,将响应正文转换为 ChatResponse 对象,并将其返回给回调方法,该对象包含了机器人对我们问题的回答信息。 ```java @Override public void onResponse(Call call, Response response) throws IOException { try { Gson gson = new Gson(); ChatResponse chatResponse = gson.fromJson(response.body().string(), ChatResponse.class); api.success(chatResponse); } catch (Exception e) { api.failure(e); } } ``` 6. 使用接口 将以上方法的代码写在一个独立的类中,调用该类的 sendRequest 方法即可。 ```java RestApi api = new RestApi() { @Override public void success(ChatResponse response) { // 处理响应数据 } @Override public void failure(Exception e) { // 处理请求失败错误信息 } }; TuringRobotApi.getInstance().sendRequest("你好", api); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值