I am trying to invoke the POST API of personality insights from Android on a button click and display the response on the screen after proper parsing. The API details of the personality insights are here.
When I tried to test this using POSTMAN I am getting the correct response. But when I try to invoke this from Android, the logcat is not showing any error and the application doesn't terminate in the emulator. The initial invocation of API is not working for me.
I referred this link for the android code
This is the code which I used. Please let me know of any mistakes that I have made.
Edited :
I also tried this example link but everything seems to be deprecated for my current android API versions.
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);
}
}
It does not seem you are sending your
contentItems
object anywhere - you populate it, but never include it as payload in the request.In addition, this
contentItems
is just one item object you need to include in the JSON input. The JSON input should look like:and you are just creating something that fits as one of the items above.
If you are passing some simple input to the API, I would suggest you include the header
Content-Type: text/plain
and forget about JSON formatting for the moment, as it is going to be simpler.