Java 用于Android应用程序示例的Watson Personal Insights服务

Java 用于Android应用程序示例的Watson Personal Insights服务,java,android,ibm-cloud,ibm-watson,personality-insights,Java,Android,Ibm Cloud,Ibm Watson,Personality Insights,我想使用IBM的个性洞察服务。我下载了Hello Wold示例代码,并尝试将个性洞察服务集成到其中 我的代码如下 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.widge

我想使用IBM的个性洞察服务。我下载了Hello Wold示例代码,并尝试将个性洞察服务集成到其中

我的代码如下

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.
    }
}
我已经参考了下面的链接

我犯了一个错误


注意:我已为Personal Insights服务设置了正确的用户名和密码。看起来您正在使用
java包装器:1.0.3
。这已经很旧了,自发布以来,我们对库进行了大量的修复和改进。 401表示您没有提供正确的凭据或服务URL不正确。您可以通过调用
service.setEndPoint()

请参见下面的示例:

将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);
PersonalityInsights服务=新建PersonalityInsights();
service.setUserName和密码(“,”);
service.setEndPoint(“https://gateway.watsonplatform.net/personality-insights/api")
String text=“您的文本在此处…”
ProfileOptions=newprofileoptions.Builder()
.文本(文本)
.build();
Profile=service.Profile(选项).execute();
系统输出打印LN(配置文件);
确保您拥有个性洞察服务(
分层
计划)的凭据。如果您需要帮助,请查看此信息。

最后,您的服务凭据不是您的Bluemix凭据。

欢迎使用SO。请编辑问题并将代码缩减为MCVE。请参阅例外情况,说明您未提供正确的凭据!但我有正确的证件。这是个性洞察服务的凭证,不是吗?@user26422282我假设您在这一行服务上设置了凭证;使用您的用户名和密码,您可以在bluemix应用程序中的Environment variables下从VCAP_服务获取这些信息。实际上,我是按照此[获取服务凭据。当时我收到了无效凭据错误。然后我在bluemix中创建了新应用程序,并按照上面的YOUTUBE链接获取了此信息[错误。我已按照您的建议更改了服务凭据。但我得到了相同的服务凭据(如上所述)错误。@Dudipls通读了评论,这家伙传递了凭证错误。问题没有更新以反映他在任何情况下都需要更新库。我编写了库,我知道他在使用Profile类时会遇到问题。我在Bluemix中新创建了应用程序和服务。但没有通过命令提示符上传。是@GermanAttanasio告诉我,我更新了库,得到了无效的凭据错误。然后我使用了凭据,这些凭据放在Bluemix应用程序中环境变量下的VCAP_服务选项卡中,正如Dudi之前告诉我的。我得到了响应。我得到了[此响应与[示例响应标题下的线程。正确吗?谢谢。但我在该响应中没有收到
word\u count
word\u count\u消息
。@Germanatanasiodid您是否检查它们是否不在打印的json末尾
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);