java调用小i机器人接口API

import java.io.IOException;
import java.util.Random;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang.StringUtils;


public class XiaoI {
private final static String APP_KEY = "*****";
private final static String APP_SECRET = "****";


public String Tess(String key, String names) {
String realm = "xiaoi.com";http://www.huiyi8.com/moban/
String method = "POST"; html模板
String uri = "/robot/ask.do";
byte[] b = new byte[20];
new Random().nextBytes(b);
String nonce = new String(Hex.encodeHex(b));
String HA1 = DigestUtils.shaHex(StringUtils.join(new String[] {
APP_KEY, realm, APP_SECRET }, ":"));
String HA2 = DigestUtils.shaHex(StringUtils.join(new String[] { method,
uri }, ":"));
String sign = DigestUtils.shaHex(StringUtils.join(new String[] { HA1,
nonce, HA2 }, ":"));


String str = null;


HttpClient hc = new HttpClient();
PostMethod pm = new PostMethod("http://nlp.xiaoi.com/robot/ask.do");
pm.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,
"utf-8");
pm.addRequestHeader("X-Auth", "app_key=\"7HHk65oE2Ngy\", nonce=\""
+ nonce + "\", signature=\"" + sign + "\"");
pm.setParameter("platform", "weixin");
pm.setParameter("type", "0");
pm.setParameter("userId", names);
pm.setParameter("question", key);
int re_code;
try {
re_code = hc.executeMethod(pm);
if (re_code == 200) {
str = pm.getResponseBodyAsString();
}
} catch (HttpException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return str;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 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. 准备提交的数据 首先我们要把url和apiKey作为成员变量定义出来: ```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、付费专栏及课程。

余额充值