从Android请求POST API的个性见解

时间:2015-08-19 11:47:35

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

我试图通过单击按钮从Android调用个性洞察的POST API,并在正确解析后在屏幕上显示响应。个性见解的API详细信息为here

当我尝试使用POSTMAN测试时,我得到了正确的响应。但是当我尝试从Android调用它时,logcat没有显示任何错误,应用程序也没有在模拟器中终止。最初调用API对我不起作用。

我将这个link称为android代码

这是我使用的代码。请让我知道我所犯的任何错误。

编辑:

我也尝试了这个例子link,但是对于我当前的Android API版本,似乎已经弃用了所有内容。

HTTP Example.java

package com.example.httpexample;
import android.support.v7.app.AppCompatActivity;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;


public class MainActivity extends AppCompatActivity {
    private TextView textView, button;
    TextView textView1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);   
        textView = (TextView) findViewById(R.id.textView1);

        button = (TextView)findViewById(R.id.button1);
        button.setOnClickListener(new View.OnClickListener(){

            // When user clicks button, calls AsyncTask.
            // Before attempting to fetch the URL, makes sure that there is a network connection.


            @Override
            public void onClick(View v) {

                String stringUrl = "https://gateway.watsonplatform.net/personality-insights/api/v2/profile" (https://gateway.watsonplatform.net/personality-insights/api/v2/profile%27);
                ConnectivityManager connMgr = (ConnectivityManager) 
                    getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
                if (networkInfo != null && networkInfo.isConnected()) {
                    new DownloadWebpageTask().execute(stringUrl);

                } else {
                    textView.setText("No network connection available.");
                }

            }
        });
    }

    public TextView getTextView()
    {

    TextView txtView = (TextView)findViewById(R.id.textView2);
    return txtView;
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}

DownloadWebpageTask.java

package com.example.httpexample;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.util.Base64;
import android.util.Log;
import android.widget.TextView;


class DownloadWebpageTask extends AsyncTask<String, Void, String> {

    private static final String DEBUG_TAG = "HttpExample";

    @Override
    protected String doInBackground(String... urls) {
        try {
            return downloadUrl(urls[0]);
        } catch (IOException e) {
            return "Unable to retrieve web page. URL may be invalid.";
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public String downloadUrl(String myurl) throws IOException, JSONException{
         InputStream is = null;


            // Only display the first 500 characters of the retrieved
            // web page content.
            int len = 500;

            try {
                URL url = new URL(myurl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                //conn.setRequestMethod("GET");
                final String basicAuth = "Basic " + Base64.encodeToString(""username":password".getBytes(), Base64.NO_WRAP);
                conn.setRequestProperty ("Authorization", basicAuth); 
                conn.setDoOutput(true); 
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/json");
                conn.connect();
                System.out.println("first connection");
                JSONObject contentItems = new JSONObject();
                contentItems.put("id", "");
                contentItems.put("userid", "");
                contentItems.put("created", "int");
                contentItems.put("updated", "int");
                contentItems.put("contenttype", "");
                contentItems.put("charset", "");
                contentItems.put("language", "int");
                contentItems.put("content", "Hi. This is the sample input");
                contentItems.put("parentid", "");
                contentItems.put("reply", false);
                contentItems.put("forward", false);
                System.out.println("connection done");
                int response = conn.getResponseCode();
                Log.d(DEBUG_TAG, "The response is: " + response);

                is = conn.getInputStream();

                // Convert the InputStream into a string
                String contentAsString = readIt(is, len);

                System.out.println("Content " + contentAsString);

                MainActivity obj = new MainActivity() ;

                TextView tv = obj.getTextView();
                tv.setText(contentAsString + response);
                return contentAsString;

            // Makes sure that the InputStream is closed after the app is
            // finished using it.
            } finally {
                if (is != null) {
                    is.close();
                } 
            }

    }



    private String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
        Reader reader = null;
        reader = new InputStreamReader(stream, "UTF-8");        
        char[] buffer = new char[len];
        reader.read(buffer);
        return new String(buffer);
    }

}

1 个答案:

答案 0 :(得分:1)

您似乎没有在任何地方发送contentItems对象 - 您填充它,但从不将其作为有效负载包含在请求中。

此外,此contentItems只是您需要包含在JSON输入中的一个项对象。 JSON输入应如下所示:

{ "contentItems": [ <item1>, <item2> ] }

并且您只是创建适合上述项目之一的内容。

如果您将一些简单的输入传递给API,我建议您包含标题Content-Type: text/plain并暂时忘记JSON格式,因为它会更简单。