java实现小i机器人api接口调用示例
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;
}
}