Почтовый HTTP-запрос к IBM Personality Insights с Android

Я хочу отправить почтовый запрос HTTP в IBM Service Personality Insight с помощью Android. Я пытался использовать этот код:

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)

Я попытаюсь установить HTTP-соединение со службой IBM, чтобы получить ответ. Однако, похоже, что это невозможно сделать. Как я могу это исправить?


person Antonio Passaro    schedule 14.05.2015    source источник


Ответы (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

person edisonthk    schedule 14.05.2015
comment
спасибо, я решил проблемы с помощью asyncTask. Теперь код работает. - person Antonio Passaro; 15.05.2015