2016-12-03 58 views
0

我正在構建一個android應用程序,我在其中調用api.ai.我想解析響應並將其顯示給用戶。早些時候,我曾寫代碼的node.js是如下:從Android調用api.ai

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代碼如下:

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); 

       } 


      } 
     }); 

     } 
    } 

我需要幫助在以下幾點:

(我)如何調用Api.ai,因爲我得到一個錯誤401?有人可以告訴如何使用Node.js代碼精確調用Api.ai嗎? (ii)如何解析響應並將其顯示給用戶?

在此先感謝

回答

3

我從Android應用程序api.ai連接。

做的步驟如下

1.添加依賴關係:

compile 'ai.api:libai:1.2.2' 
    compile 'ai.api:sdk:[email protected]' 

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); 

//請求 - 您想要發送給聊天機器人的任何字符串以獲得相應的響應。

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(); 

如果結果是一個字符串,與響應字符串將是:

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

問候。 豔女

+0

「aiRequest.setQuery(request);'中的'request'是什麼?你在哪裏定義了答案? –

0

您可以參考這裏整合API.AI的官方文檔 -

https://github.com/api-ai/apiai-android-client

編碼愉快。

+1

請確保您的答案在沒有鏈接的情況下解決問題。您應該添加一個簡短的摘要以防鏈接中斷。 –