JAVA开发微信图灵机器人【L】

首先我们先注册图灵机器人

网址:http://www.tuling123.com

注册、登录很简单,自己玩吧。

登录后

看到 APIKey 这个是开发的时候需要用到的。

上代码吧。不需要别的jar copy可用

package tuling;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

public class HtmlUtil {
	public static byte[] requestByPost(String uri, String param) {
		URL url = null;
        try {
            url = new URL(uri);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");// 提交模式
            httpURLConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            // 发送请求参数
            printWriter.write(param);//post的参数
            // flush输出流的缓冲
            printWriter.flush();
            String cookie = httpURLConnection.getHeaderField("set-cookie");
            System.out.println("cookie:::::::::::::" + cookie);
            int repCode  = httpURLConnection.getResponseCode();
            System.out.println(repCode);
            //开始获取数据
            return changeInputStream(httpURLConnection.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
	}
	
	public static byte[] changeInputStream(InputStream inputStream) {
		// TODO Auto-generated method stub
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		int len = 0;
		byte[] date = new byte[1024];
		try {
			while ((len = inputStream.read(date)) != -1) {
				outputStream.write(date, 0, len);
			}
			return outputStream.toByteArray();
			//result = new String(outputStream.toByteArray(), encode);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				outputStream.close();
				inputStream.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}
	
    public static void main(String[] args) {
		String tulingKey = "这里别忘记填写你的APIKey";
		String url = "http://www.tuling123.com/openapi/api";
		String json = "{"info":"你男的女的?","key":"
				+ ""056915e71cbe43a880c2f39ad34bf357","loc":"
				+ ""","userid":"123456"}";
		System.out.println(json);
		byte ret[] = HtmlUtil.requestByPost(url, json.toString());
		System.out.println(new String(ret));
	}
}

结果:

{"info":"你男的女的?","key":"*******************","loc":"","userid":"123456"} cookie:::::::::::::null 200 {"code":100000,"text":"喔,我是耍一点小性格,懂一点小幽默的女孩呢。"}

经验分享 程序员 微信小程序 职场和发展