问题
I would like to make an HTTP post request to IBM Service Personality Insight using Android. I tried to use this code:
private String mServer="gateway.watsonplatform.net";
private int mPort = 9081;
private String mUser= "**USERID HIDDEN**";
private String mPassword= "**PASSWORD HIDDEN**";
private HttpResponse makeRequest(String urlPath) throws Exception {
HttpClient httpclient;
HttpParams httpParameters;
HttpPost request;
int timeoutConnection = 10000;
int timeoutSocket = 10000;
httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
httpclient = new DefaultHttpClient(httpParameters);
Credentials creds = new UsernamePasswordCredentials(mUser, mPassword);
((AbstractHttpClient) httpclient).getCredentialsProvider().setCredentials(
new AuthScope(mServer, mPort), creds);
request = new HttpPost("https://gateway.watsonplatform.net/personality-insights/api/v2/profile");
HttpResponse res = httpclient.execute(request);
httpclient.getConnectionManager().shutdown();
return res;
}
private String processRequest(HttpResponse resp) throws Exception{
int status = resp.getStatusLine().getStatusCode();
if (status == 200){
//Get the body
return getBodyFromResponse(resp);
} else if (status == 400) {
//Bad Request
throw new Exception("Error: HTTP 400 error");
} else if (status == 401) {
//Unauthorized
throw new Exception("Error: HTTP 401 error: Incorrect Server Name");
} else if (status == 403) {
//Forbidden
throw new Exception("Error: HTTP 403 error: Check UserName and password");
} else if (status == 500) {
//Internal Server Error
throw new Exception("Error: HTTP 500 error");
} else {
throw new Exception("Error Unknown: Status is " + status);
}
}
//HTTP Response is passed in, and the JSON String from the Body is returned
private String getBodyFromResponse(HttpResponse resp) throws Exception{
ResponseHandler<String> handler = new BasicResponseHandler();
try {
return handler.handleResponse(resp);
} catch (IOException e) {
throw new Exception ("Error: HTTP Response 200. Error when converting response. " + e.getMessage());
} catch (Exception e) {
throw new Exception ("Error: HTTP Response 200. Error when converting response. " + e.getMessage());
}
}
However, I got these errors:
05-14 17:19:36.124 29241-29241/com.example.antonio.helloword W/System.err﹕ android.os.NetworkOnMainThreadException
05-14 17:19:36.194 29241-29241/com.example.antonio.helloword W/System.err﹕ at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
05-14 17:19:36.194 29241-29241/com.example.antonio.helloword W/System.err﹕ at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
05-14 17:19:36.194 29241-29241/com.example.antonio.helloword W/System.err﹕ at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
05-14 17:19:36.194 29241-29241/com.example.antonio.helloword W/System.err﹕ at java.net.InetAddress.getAllByName(InetAddress.java:214)
05-14 17:19:36.194 29241-29241/com.example.antonio.helloword W/System.err﹕ at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
05-14 17:19:36.194 29241-29241/com.example.antonio.helloword W/System.err﹕ at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
05-14 17:19:36.194 29241-29241/com.example.antonio.helloword W/System.err﹕ at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
05-14 17:19:36.194 29241-29241/com.example.antonio.helloword W/System.err﹕ at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
05-14 17:19:36.194 29241-29241/com.example.antonio.helloword W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
05-14 17:19:36.194 29241-29241/com.example.antonio.helloword W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
05-14 17:19:36.194 29241-29241/com.example.antonio.helloword W/System.err﹕ at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
05-14 17:19:36.194 29241-29241/com.example.antonio.helloword W/System.err﹕ at com.example.giovanni.helloword.Login.makeRequest(Login.java:115)
05-14 17:19:36.194 29241-29241/com.example.antonio.helloword W/System.err﹕ at com.example.giovanni.helloword.Login.onCreate(Login.java:68)
05-14 17:19:36.194 29241-29241/com.example.antonio.helloword W/System.err﹕ at android.app.Activity.performCreate(Activity.java:5047)
05-14 17:19:36.194 29241-29241/com.example.antonio.helloword W/System.err﹕ at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
05-14 17:19:36.194 29241-29241/com.example.antonio.helloword W/System.err﹕ at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2056)
05-14 17:19:36.194 29241-29241/com.example.antonio.helloword W/System.err﹕ at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2117)
05-14 17:19:36.194 29241-29241/com.example.antonio.helloword W/System.err﹕ at android.app.ActivityThread.access$700(ActivityThread.java:134)
05-14 17:19:36.194 29241-29241/com.example.antonio.helloword W/System.err﹕ at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1218)
05-14 17:19:36.194 29241-29241/com.example.antonio.helloword W/System.err﹕ at android.os.Handler.dispatchMessage(Handler.java:99)
05-14 17:19:36.194 29241-29241/com.example.antonio.helloword W/System.err﹕ at android.os.Looper.loop(Looper.java:137)
05-14 17:19:36.194 29241-29241/com.example.antonio.helloword W/System.err﹕ at android.app.ActivityThread.main(ActivityThread.java:4867)
05-14 17:19:36.194 29241-29241/com.example.antonio.helloword W/System.err﹕ at java.lang.reflect.Method.invokeNative(Native Method)
05-14 17:19:36.194 29241-29241/com.example.antonio.helloword W/System.err﹕ at java.lang.reflect.Method.invoke(Method.java:511)
05-14 17:19:36.194 29241-29241/com.example.antonio.helloword W/System.err﹕ at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1007)
05-14 17:19:36.194 29241-29241/com.example.antonio.helloword W/System.err﹕ at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:774)
05-14 17:19:36.194 29241-29241/com.example.antonio.helloword W/System.err﹕ at dalvik.system.NativeStart.main(Native Method)
I will try to make an HTTP connection to IBM service to get the response. However, it looks like it's impossible to do. How can I fix it?
回答1:
Your problems are quite common as Android beginner. As the log, android.os.NetworkOnMainThreadException
stated that you are doing your network task on main thread which is not allowable. You have to do network task in background otherwise you can't get away from the errors. You can fix this problems by wrapping your current code with AsyncTask
.
private class MyAsycnTask extends AsyncTask<String, String, String> {
private String process = null;
protected String doInBackground(String... urls) {
// do your network task in background
HttpResponse res = makeRequest(urls[0]);
this.process = processRequest(res);
return getBodyFromResponse(res);
}
protected void onPostExecute(String responseBody) {
// do your UI task in main thread
showDialog("Downloaded " + result + " bytes");
}
/*
The rest of your code are below here
....
*/
}
You should understand the relationship between background and main thread, or else you can't understand why AsyncTask is needed in networking. For more details about AsyncTask, please take a looks at docs.
http://developer.android.com/reference/android/os/AsyncTask.html
来源:https://stackoverflow.com/questions/30241156/http-post-request-to-ibm-personality-insights-with-android