从Android调用api.ai [英] Calling api.ai from Android

查看:97
本文介绍了从Android调用api.ai的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在构建一个我要调用api.ai的android应用。我想解析响应并将其显示给用户。先前我在node.js中编写了以下代码:

I am building an android app in which I am calling api.ai. I want to parse the response and display it to users. Earlier I had written code in node.js which is as below:

    function sendMessageToApiAi(options,botcontext) {
        var message = options.message; // Mandatory
        var sessionId = options.sessionId || ""; // optinal
        var callback = options.callback;
        if (!(callback && typeof callback == 'function')) {
           return botcontext.sendResponse("ERROR : type of options.callback should be function and its Mandatory");
        }
        var nlpToken = options.nlpToken;

        if (!nlpToken) {
           if (!botcontext.simpledb.botleveldata.config || !botcontext.simpledb.botleveldata.config.nlpToken) {
               return botcontext.sendResponse("ERROR : token not set. Please set Api.ai Token to options.nlpToken or context.simpledb.botleveldata.config.nlpToken");
           } else {
               nlpToken = botcontext.simpledb.botleveldata.config.nlpToken;
           }
        }
        var query = '?v=20150910&query='+ encodeURIComponent(message) +'&sessionId='+context.simpledb.roomleveldata.c1+'&timezone=Asia/Calcutta&lang=en    '
        var apiurl = "https://api.api.ai/api/query"+query;
        var headers = { "Authorization": "Bearer " + nlpToken};
        botcontext.simplehttp.makeGet(apiurl, headers, function(context, event) {
           if (event.getresp) {
               callback(event.getresp);
           } else {
               callback({})
           }
        });
    }

我的Android代码如下:

My Android code is as below:

package com.example.pramod.apidev;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity{
    private Button listenButton;
    private TextView resultTextView;
    private EditText inputText;
    private static String API_URL = "https://api.api.ai/api/query";
    private static String API_KEY = "d05b02dfe52f4b5f969ba1257cffac37";
    private static String query;
    private static String s;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listenButton = (Button) findViewById(R.id.listenButton);

        resultTextView = (TextView) findViewById(R.id.resultTextView);
        inputText = (EditText)findViewById(R.id.inputText);

        s = inputText.getText().toString();


        query = "?v=20150910&query=hi" +"&sessionId=1480181847573api&timezone=Asia/Calcutta&lang=en";
        listenButton.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                try {


                    URL url = new URL(API_URL + query + "&apiKey=" + API_KEY);
                    HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
                }
                catch(Exception e) {
                    Log.e("ERROR", e.getMessage(), e);

                }


            }
        });

        }
    }

我需要以下帮助:

(i)由于出现错误401,如何调用Api.ai?

(i) How can call the Api.ai since I am getting an error 401? Can some one tell how to exactly call Api.ai using the Node.js code?

(ii)如何解析响应并将其显示给用户?

(ii) How can parse the response and display it to users?

预先感谢

推荐答案

我正在从android连接api.ai应用程序。

I'm connecting with api.ai from android app.

要做的步骤如下

1。添加依赖项:

    compile 'ai.api:libai:1.2.2'
    compile 'ai.api:sdk:2.0.1@aar'

2。创建一个实现AIListener的活动。

3。声明AIService和AIDataService:

    private AIService aiService;
    private AIDataService aiDataService;

4。初始化配置,服务并添加侦听器:

    final ai.api.android.AIConfiguration config = new       ai.api.android.AIConfiguration("API_KEY",
        ai.api.android.AIConfiguration.SupportedLanguages.Spanish,
        ai.api.android.AIConfiguration.RecognitionEngine.System);

    // Use with text search
    aiDataService = new AIDataService(this, config);

    // Use with Voice input
    aiService = AIService.getService(this, config);

    aiService.setListener(this);

5。执行异步任务以发出请求:

    AIRequest aiRequest = new AIRequest();

    aiRequest.setQuery(request); 

//请求-您要发送给聊天机器人的任何字符串,以得到相应的响应。

//request--any string you want to send to chat bot to get there corresponding response.

    if(aiRequest==null) {
        throw new IllegalArgumentException("aiRequest must be not null");
    }

    final AsyncTask<AIRequest, Integer, AIResponse> task =
        new AsyncTask<AIRequest, Integer, AIResponse>() {
                    private AIError aiError;

    @Override
    protected AIResponse doInBackground(final AIRequest... params) {
        final AIRequest request = params[0];
            try {
                final AIResponse response =    aiDataService.request(request);
                // Return response 
                return response;
            } catch (final AIServiceException e) {
                aiError = new AIError(e);
                return null;
            }
        }

    @Override
    protected void onPostExecute(final AIResponse response) {
        if (response != null) {
            onResult(response);
        } else {
            onError(aiError);
        }
    }
};
task.execute(aiRequest);

6。 onResult方法

Result result = response.getResult();

如果结果是字符串,则带有响应的字符串将位于:

If the result is a string, the string with the response will be in:

String speech = result.getFulfillment().getSpeech();

致谢。
Nuria

Regards. Nuria

这篇关于从Android调用api.ai的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆