0

スマートフォンにインストールされた Android アプリと通信するサーバーを使用しています。アプリはローカル環境で使用されており、コンピューターのローカル IP を使用して Wi-Fi 経由で Apache サーバーと通信します。

問題は、ローカル IP が時々変更されることです。これが数回後に発生すると、操作のタイムアウトが原因で、NullPointer 例外が原因でアプリがクラッシュします。したがって、サーバーへの接続がいつ失敗したかを知る方法があるかどうか、および(操作のタイムアウトを確認した後)アプリが動作しないように何らかのアクションを実行する方法があるかどうかを知りたい氷結。

事前にt​​hnx

このコードを使用して接続します。

HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);


        JSONObject jo = new JSONObject();
        jo.put("tag",tag);




        // Prepare JSON to send by setting the entity
        httpPost.setEntity(new StringEntity(jo.toString(), "UTF-8"));

        // Set up the header types needed to properly transfer JSON
        httpPost.setHeader("Content-Type", "application/json");
        httpPost.setHeader("Accept-Encoding", "application/json");
        httpPost.setHeader("Accept-Language", "en-US");
        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity entity = response.getEntity();


            is = entity.getContent();

そして、これから最終的にjsonObjectが返され、その後、必要なものを取得するために解析します。

4

2 に答える 2

1

http 呼び出しを行うには非同期タスクを使用する必要があります。そうしないと、操作が完了するまでアプリがフリーズします。

単純な sysnc クラスから始めて、http 要求を実行します。また、結果を返すためにある種のハンドラーが必要です。タスクが完了したら、ユーザー インターフェイスまたは Androidハンドラーを使用できます。インターフェイスが好きです。

class MyHttpTask extends AsyncTask<View, View, String>
{
    String url = null;
    HttpResultHandler handler = null;
            public final static int ERROR_CONNECTION_TIMEOUT = 1000;
            public final static int ERROR_SOCKET_TIMEOUT     = 2000;
            private int error_code = 0;

    public MyHttpTask(String url, HttpResultHandler handler)
    {
        this.url = url;
        this.handler = handler;
    }

    @Override
    protected String doInBackground(View... arg0)
    {
        try
        {
            HttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            JSONObject jo = new JSONObject();
            jo.put("tag", tag);

            // Prepare JSON to send by setting the entity
            httpPost.setEntity(new StringEntity(jo.toString(), "UTF-8"));

            // Set up the header types needed to properly transfer JSON
            httpPost.setHeader("Content-Type", "application/json");
            httpPost.setHeader("Accept-Encoding", "application/json");
            httpPost.setHeader("Accept-Language", "en-US");
            HttpResponse response = httpClient.execute(httpPost);
            HttpEntity entity = response.getEntity();

            InputStream is = entity.getContent();

            String result = // read your stream as string or any you might prefer byte[]

            return result;
        }
        catch (UnresolvedAddressException e)
        {
            return null;
        }
        catch (UnknownHostException e)
        {
            return null;
        }
            catch (ConnectTimeoutException e)
             {
                    error_code = ERROR_CONNECTION_TIMEOUT;
                    return null;
             }
           catch(SocketTimeoutException e)
            {
                    error_code = ERROR_SOCKET_TIMEOUT;
                    return null;
            }
        catch (IOException e)
        {
            return null;
        }
        catch (Exception e)
        {
            return null;
        }
    }

    @Override
    protected void onPostExecute(String result)
    {
        if (result!=null)
        {
            handler.onSuccess(result);
        }
        else
        {
            handler.OnFailure(errorCode);
        }
    }
}

操作の成功または失敗を報告する単純なインターフェイスを次に示します。

static interface HttpResultHandler
{
    public void onSuccess(String result);

    public void OnFailure(int errorCode);
}

ソリューションをテストするには:

private void testHttpTask()
{
     // here you can block the UI using any type of progress bar
    String url = "http://www.something.com";
    new MyHttpTask(url, new HttpResultHandler()
    {

        @Override
        public void onSuccess(String result)
        {
            // TODO Auto-generated method stub
              // here you get success result
             // dismiss any loading progress bars
        }

        @Override
        public void OnFailure(int error_code)
        {
            // TODO Auto-generated method stub
                    // here you get failure
            // dismiss any loading progress bars, and do your recovery stuff

        }
    }).execute();
}
于 2013-10-16T21:12:39.893 に答える
0

接続を確立する場所にコードを配置します。あなたが説明したことから、タイムアウトを決定し、それを何らかの方法でキャッチできるように、httpパラメーターを設定する必要があるように思えます。

于 2013-10-16T19:54:53.573 に答える