Java调用图灵机器人聊天

       在网上找的聊天都是我问一句,下一句就接不上来了,就连成语接龙都玩不了,后来发现问题就出在userid这个参数上面,以下就是能够进行连续聊天的代码,懒得写界面,聊天字符串每执行一次就自己改一下,懒得写input,与网上大多数不同的是我在url中添加了一个userid参数,重点就是url这个字符串,其他的一模一样,应该可以自己添加groupID和userIdName。代码如下。

        userid参数是自己随便写的,apiKey需要你自己去申请,自行百度“图灵机器人的申请”等词条,或图灵机器人官网,如果只是实验可以用我这个,但是最好自己去申请一个,免费的哈。

package tulingTest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class UrlFinish {
	public static void main(String[] args) throws IOException {
		String question = "重庆市大学城附近的酒店";
		String info = URLEncoder.encode(question, "utf-8");
		String apiKey = "b6cc890990a04f23a6c6c71a4c36fb4c";
		String userId = "123456";
		String url = "http://www.tuling123.com/openapi/api?key="+apiKey
				+"&info="+info+"&userid="+userId;
		URL getUrl = new URL(url);
		HttpURLConnection connection = (HttpURLConnection)getUrl.openConnection();
		connection.connect();
		
//		获得输入流,并使用Reader读取
		BufferedReader reader = new BufferedReader(
				new InputStreamReader(connection.getInputStream(),"utf-8"));
		StringBuffer stringBuffer = new StringBuffer();
		String line = "";
		while((line = reader.readLine()) != null){
			stringBuffer.append(line);
		}		
//		断开reader
		reader.close();
//		断开链接
		connection.disconnect();
		System.out.println(stringBuffer);	
		responseAnalysis(stringBuffer);
	}
	
	private static void responseAnalysis(StringBuffer str){
		String string = str.toString();
//		返回的是索引
		int textBegin = string.indexOf("\"text");
		int urlBegin = string.indexOf("\"url");
		int codeBegin = string.indexOf("\"code");
		System.out.println(textBegin);
		System.out.println(urlBegin);
		System.out.println(codeBegin);
		if(textBegin != -1)
			System.out.println(string.substring(textBegin, urlBegin));
		if(urlBegin != -1)
			System.out.println(string.substring(urlBegin));
		if(codeBegin != -1)
			System.out.println(string.substring(codeBegin,textBegin));
		
	}
}

 

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); ```
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值