欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

java实现小i机器人api接口调用示例

程序员文章站 2024-03-31 12:46:46
复制代码 代码如下:package com.weixin.util; import java.io.ioexception;import java.util.random...

复制代码 代码如下:

package com.weixin.util;

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";
  string method = "post";
  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;
 }
}