您好,我正在创建一个将通过物联网与产品进行交互的APP。基本上,当用户说出“更改温度” 之类的关键字时,应用程序将调用一个API,而该API将进行更改。
我正在使用DialogFlow示例,但无法调用BlueMix API(https://secureauth.wcloud.us-south.containers.mybluemix.net/oauth/token) 但它不起作用。
这是我正在使用的代码
/**
* Copyright 2017 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ai.api.sample;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.JsonWriter;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonDeserializer;
import com.google.gson.JsonElement;
import com.google.gson.JsonIOException;
import com.google.gson.JsonObject;
import com.google.gson.JsonSerializationContext;
import com.google.gson.stream.JsonReader;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import ai.api.android.AIConfiguration;
import ai.api.android.GsonFactory;
import ai.api.model.AIError;
import ai.api.model.AIResponse;
import ai.api.model.Metadata;
import ai.api.model.Result;
import ai.api.model.Status;
import ai.api.ui.AIButton;
import org.json.JSONObject;
import org.json.JSONArray;
import android.os.AsyncTask;
import javax.net.ssl.HttpsURLConnection;
public class AIButtonSampleActivity extends BaseActivity implements AIButton.AIButtonListener {
public static final String TAG = AIButtonSampleActivity.class.getName();
private AIButton aiButton;
private TextView resultTextView;
private final String link = "https://secureauth.wcloud.us-south.containers.mybluemix.net/oauth/token";
Context contx;
private Gson gson = GsonFactory.getGson();
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_aibutton_sample);
resultTextView = (TextView) findViewById(R.id.resultTextView);
aiButton = (AIButton) findViewById(R.id.micButton);
final AIConfiguration config = new AIConfiguration(Config.ACCESS_TOKEN,
AIConfiguration.SupportedLanguages.PortugueseBrazil,
AIConfiguration.RecognitionEngine.System);
config.setRecognizerStartSound(getResources().openRawResourceFd(R.raw.test_start));
config.setRecognizerStopSound(getResources().openRawResourceFd(R.raw.test_stop));
config.setRecognizerCancelSound(getResources().openRawResourceFd(R.raw.test_cancel));
aiButton.initialize(config);
aiButton.setResultsListener(this);
}
@Override
protected void onPause() {
super.onPause();
// use this method to disconnect from speech recognition service
// Not destroying the SpeechRecognition object in onPause method would block other apps from using SpeechRecognition service
aiButton.pause();
}
@Override
protected void onResume() {
super.onResume();
// use this method to reinit connection to recognition service
aiButton.resume();
}
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
getMenuInflater().inflate(R.menu.menu_aibutton_sample, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(final MenuItem item) {
final int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
startActivity(AISettingsActivity.class);
return true;
}
return super.onOptionsItemSelected(item);
}
@Override
public void onResult(final AIResponse response) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.d(TAG, "onResult");
Log.i(TAG, "Received success response");
// this is example how to get different parts of result object
final Status status = response.getStatus();
Log.i(TAG, "Status code: " + status.getCode());
Log.i(TAG, "Status type: " + status.getErrorType());
final Result result = response.getResult();
Log.i(TAG, "Resolved query: " + result.getResolvedQuery());
Log.i(TAG, "Action: " + result.getAction());
final String speech = result.getFulfillment().getSpeech();
Log.i(TAG, "Speech: " + speech);
final String actionID = result.getMetadata().getIntentId();
if ( actionID.equalsIgnoreCase("343bed1b-c472-4b66-8d34-f2f7a322727f") ){
resultTextView.setText("deu certo a locuragem");
try {
ApiCalling();
} catch (IOException e) {
e.printStackTrace();
}
}
else{
resultTextView.setText(speech);
}
TTS.speak(speech);
final Metadata metadata = result.getMetadata();
if (metadata != null) {
Log.i(TAG, "Intent id: " + metadata.getIntentId());
Log.i(TAG, "Intent name: " + metadata.getIntentName());
}
final HashMap<String, JsonElement> params = result.getParameters();
if (params != null && !params.isEmpty()) {
Log.i(TAG, "Parameters: ");
for (final Map.Entry<String, JsonElement> entry : params.entrySet()) {
Log.i(TAG, String.format("%s: %s", entry.getKey(), entry.getValue().toString()));
}
}
}
});
}
@Override
public void onError(final AIError error) {
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.d(TAG, "onError");
resultTextView.setText(error.toString());
}
});
}
@Override
public void onCancelled() {
runOnUiThread(new Runnable() {
@Override
public void run() {
Log.d(TAG, "onCancelled");
resultTextView.setText("");
}
});
}
private void startActivity(Class<?> cls) {
final Intent intent = new Intent(this, cls);
startActivity(intent);
}
private void ApiCalling() throws IOException {
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
URL strEndpoint = null;
strEndpoint = new URL("https://secureauth.wcloud.us-south.containers.mybluemix.net/oauth/token");
// Create connection
HttpsURLConnection myConnection =(HttpsURLConnection) strEndpoint.openConnection();
// Create the data
myConnection.setDoInput(true);
myConnection.setDoOutput(true);
myConnection.setRequestMethod("POST");
myConnection.setRequestProperty("grant_type", "password");
myConnection.setRequestProperty("client_id", "IOT");
myConnection.setRequestProperty("client_secrect", "test12");
myConnection.setRequestProperty("username", "iotbot@gmail.com");
myConnection.setRequestProperty("password", "Test123");
myConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
if (myConnection.getResponseCode() == 200) {
InputStream responseBody = myConnection.getInputStream();
InputStreamReader responseBodyReader =
new InputStreamReader(responseBody, "UTF-8");
JsonReader jsonReader = new JsonReader(responseBodyReader);
} else {
// Error handling code goes here
}
} catch (IOException e) {
e.printStackTrace();
Log.i(TAG, e.getMessage() );
String str;
str="teste";
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
private static String readStream(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
Log.e(TAG, "IOException", e);
} finally {
try {
is.close();
} catch (IOException e) {
Log.e(TAG, "IOException", e);
}
}
return sb.toString();
}
}
我也尝试过使用JsonObject,但它也无法正常工作jason.addProperty("client_id", "test");
如何使用POST方法调用此API?