1

我想使用 Android 向 IBM Service Personality Insight 发出 HTTP 发布请求。我尝试使用此代码:

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());
    }
}

但是,我收到了这些错误:

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)

我将尝试与 IBM 服务建立 HTTP 连接以获取响应。然而,这似乎是不可能的。我该如何解决?

4

1 回答 1

1

作为 Android 初学者,您的问题很常见。作为日志,android.os.NetworkOnMainThreadException说明您正在主线程上执行网络任务,这是不允许的。您必须在后台执行网络任务,否则您无法摆脱错误。您可以通过使用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 
        ....
     */
 }

你应该了解后台和主线程之间的关系,否则你无法理解为什么在网络中需要 AsyncTask。有关 AsyncTask 的更多详细信息,请查看文档。

http://developer.android.com/reference/android/os/AsyncTask.html

于 2015-05-14T17:05:59.780 回答