我试图通过单击按钮从Android调用个性洞察的POST API,并在正确解析后在屏幕上显示响应。个性洞察的 API 详细信息在此处。
当我尝试使用 POSTMAN 对此进行测试时,我得到了正确的响应。但是当我尝试从 Android 调用它时,logcat 没有显示任何错误,并且应用程序不会在模拟器中终止。API 的初始调用对我不起作用。
我参考了这个链接以获取 android 代码
这是我使用的代码。请让我知道我犯的任何错误。
编辑:
我也尝试了这个示例链接,但对于我当前的 android API 版本,一切似乎都已被弃用。
HTTP 示例.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);
}
}
下载WebpageTask.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);
}
}