【问题标题】:Watson Personality Insights Service for Android Application Sample适用于 Android 应用程序示例的 Watson Personality Insights Service
【发布时间】:2016-01-19 10:36:04
【问题描述】:

我想使用 IBM 的 Personality Insights Service。我已经下载了 Hello Wold 示例代码并尝试在其中集成 Personality Insights Service

我的代码如下。

MainActivity.java

package com.ibm.bms.samples.android.helloworld;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.ibm.mobilefirstplatform.clientsdk.android.core.api.BMSClient;
import com.ibm.mobilefirstplatform.clientsdk.android.core.api.Request;
import com.ibm.mobilefirstplatform.clientsdk.android.core.api.Response;
import com.ibm.mobilefirstplatform.clientsdk.android.core.api.ResponseListener;
import com.ibm.watson.developer_cloud.personality_insights.v2.PersonalityInsights;
import com.ibm.watson.developer_cloud.personality_insights.v2.model.Profile;

import org.json.JSONObject;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.net.MalformedURLException;
import java.net.UnknownHostException;

public class MainActivity extends Activity implements ResponseListener {

    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView buttonText = (TextView) findViewById(R.id.button_text);

        try {
            //initialize SDK with IBM Bluemix application ID and route
            //TODO: Please replace <APPLICATION_ROUTE> with a valid ApplicationRoute and <APPLICATION_ID> with a valid ApplicationId
            BMSClient.getInstance().initialize(this, "http://bluemixpersonality.mybluemix.net", "b8c06c80-83fa-4448-b770-3ff5b3f1fb84");
        } catch (MalformedURLException mue) {
            this.setStatus("Unable to parse Application Route URL\n Please verify you have entered your Application Route and Id correctly and rebuild the app", false);
            buttonText.setClickable(false);
        }
    }

    public void pingBluemix(View view) {

        TextView buttonText = (TextView) findViewById(R.id.button_text);
        buttonText.setClickable(false);

        TextView errorText = (TextView) findViewById(R.id.error_text);
        errorText.setText("Pinging Bluemix");

        Log.i(TAG, "Pinging Bluemix");

        // Testing the connection to Bluemix by sending a Get request to the Node.js application, using this Activity to handle the response.
        // This Node.js code was provided in the MobileFirst Services Starter boilerplate.
        // The below request uses the IBM Mobile First Core sdk to send the request using the applicationRoute that was provided when initializing the BMSClient earlier.
        new Request(BMSClient.getInstance().getBluemixAppRoute(), Request.GET).send(this.getApplicationContext(), this);
    }

    private void setStatus(final String messageText, boolean wasSuccessful) {
        final TextView errorText = (TextView) findViewById(R.id.error_text);
        final TextView topText = (TextView) findViewById(R.id.top_text);
        final TextView bottomText = (TextView) findViewById(R.id.bottom_text);
        final TextView buttonText = (TextView) findViewById(R.id.button_text);
        final String topStatus = wasSuccessful ? "Yay!" : "Bummer";
        final String bottomStatus = wasSuccessful ? "You Are Connected" : "Something Went Wrong";

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                buttonText.setClickable(true);
                errorText.setText(messageText);
                topText.setText(topStatus);
                bottomText.setText(bottomStatus);
            }
        });
    }

    // Implemented for the response listener to handle the success response when Bluemix is pinged
    @Override
    public void onSuccess(Response response) {

        Log.e("Response: ", response.getResponseText());

        String myProfile = "Call me Ishmael. Some years ago-never mind how long precisely-having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world. It is a way I have of driving off the spleen and regulating the circulation. Whenever I find myself growing grim about the mouth; whenever it is a damp, drizzly November in my soul; whenever I find myself involuntarily pausing before coffin warehouses, and bringing up the rear of every funeral I meet; and especially whenever my hypos get such an upper hand of me, that it requires a strong moral principle to prevent me from deliberately stepping into the street, and methodically knocking people's hats off-then, I account it high time to get to sea as soon as I can.";

        PersonalityInsights service = new PersonalityInsights();
        service.setUsernameAndPassword("{username}","{password}");

        Profile personalityProfile = service.getProfile(myProfile);
        Log.e("hahah: ", "" + personalityProfile);

        setStatus("", true);
        Log.i(TAG, "Successfully pinged Bluemix!");
    }

    // Implemented for the response listener to handle failure response when Bluemix is pinged
    @Override
    public void onFailure(Response response, Throwable throwable, JSONObject jsonObject) {
        // Blah Blah Code on Failing to connect to IBM.
    }
}

build.gradle

    apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.0"

    defaultConfig {
        applicationId "com.ibm.bms.samples.android.helloworld"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    packagingOptions {
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/DEPENDENCIES'
        exclude 'META-INF/NOTICE'
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.0.0'
    compile group: 'com.ibm.mobilefirstplatform.clientsdk.android',
            name: 'core',
            version: '1.+',
            ext: 'aar',
            transitive: true
    compile 'com.ibm.watson.developer_cloud:java-wrapper:1.0.3'
}

我已经参考了下面的链接。

How to call Watson Insights Service using java

我收到以下错误。

Error Image

注意:我已为 Personality Insights Service 设置了正确的用户名和密码。

【问题讨论】:

  • 欢迎来到 SO。请编辑问题并将您的代码简化为 MCVE。见stackoverflow.com/help/mcve
  • 异常表示您没有提供正确的凭据!
  • 但我输入了正确的凭据。这是 Personality Insights Service 的凭证,不是吗?@user2642282
  • 我假设你在这条线上设置了信誉 service.setUsernameAndPassword("{username}","{password}");使用您的用户名和密码,您可以在 bluemix 应用程序的环境变量下从 VCAP_SERVICES 获取这些信息
  • 其实我是在关注这个 [youtube.com/watch?v=B_m3mBadUrQ] 来获取服务凭证。那时我收到了 INVALID CREDENTIAL 错误。然后我在 BlueMix 中制作了新应用程序并按照上面的 YOUTUBE 链接并得到了这个 [i.imgur.com/L0iyGkc.png] 错误。我已按照您的建议更改了服务凭据。但我得到了同样的(ABOVE)错误。@Dudi

标签: java android ibm-cloud ibm-watson personality-insights


【解决方案1】:

看起来您正在使用java-wrapper:1.0.3。那已经很老了,自该版本以来,我们对库进行了很多修复和改进。 401 表示您没有提供正确的凭据或服务 URL 不正确。可以通过调用service.setEndPoint()设置服务URL

请看下面的例子:

将gradle中的依赖更新为:

'com.ibm.watson.developer_cloud:java-sdk:5.3.0'

然后使用这个代码:

PersonalityInsights service = new PersonalityInsights();
service.setUsernameAndPassword("<username>", "<password>");
service.setEndPoint("https://gateway.watsonplatform.net/personality-insights/api")

String text = "your text goes here...."
ProfileOptions options = new ProfileOptions.Builder()
  .text(text)
  .build();

Profile profile = service.profile(options).execute();
System.out.println(profile);

确保您拥有 Personality Insights 服务(tiered 计划)的凭据。如果您需要帮助,请查看此guide
最后,您的服务凭证不是您的 Bluemix 凭证。

【讨论】:

  • 请通读 cmets,这家伙通过了凭据错误。该问题未更新以反映它
  • 无论如何他都需要更新库。我写了这个库,我知道他在使用 Profile 类时会遇到问题。
  • 我在 Bluemix 中新创建了应用程序和服务。但不是通过命令提示符上传的。是的,正如@GermanAttanasio 所说,我已经更新了 LIBRARY 并收到了 INVALID CREDENTIAL 错误。正如 Dudi 之前所说,我使用的凭据位于我的 Bluemix 应用程序中 ENVIRONMENT VARIABLE 下的 VCAP_SERVICES 选项卡中。我得到了响应。我得到 [i.imgur.com/mR29kU2.png] 这个响应与 Example response 标题下的 [ibm.com/smarterplanet/us/en/ibmwatson/developercloud/… 线程不同。是正确的 res 吗?
  • 谢谢。但我没有收到 word_countword_count_message 在那个回复中。@GermanAttanasio
  • 你检查它们是否不在打印的json的末尾
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-05-13
  • 1970-01-01
  • 1970-01-01
  • 2016-11-21
  • 2018-01-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多