0

テキスト ボックスから取得した URL への単純な HTTP ヘッド リクエストを作成したいと考えています。URL を入力してクリックして HTTP 応答を取得するたびに、アプリが応答しなくなります。コードは次のとおりです。

public  void    MakeRequest(View v)
{
    EditText mEdit;
    TextView txtresponse;
    txtresponse = (TextView)findViewById(R.id.textView1);
    mEdit = (EditText)findViewById(R.id.editText1);
    HttpClient httpClient = new DefaultHttpClient();
    HttpHead httphead = new HttpHead(mEdit.getText().toString());

    try {
        HttpResponse response = httpClient.execute(httphead);
        txtresponse.setText(response.toString());
    } catch (ClientProtocolException e) {
        // writing exception to log
        e.printStackTrace();
    } catch (IOException e) {
        // writing exception to log
        e.printStackTrace();

    }
}
4

2 に答える 2

1

UI スレッドで実行時間の長いタスクを実行しないでください (また、HTTP 要求/応答は、サーバーの待ち時間のために非常に時間がかかる場合があります)。バックグラウンド スレッドで HTTP 処理を実行します。Stackoverflow にはいくつかの例があります - Make an HTTP request with androidのように、もちろん Android サイトで読んでください - http://developer.android.com/training/articles/perf-anr.html

于 2014-01-05T19:18:33.477 に答える
0

おそらくUIスレッドでリクエストを行っています。UI のために行われるすべての作業を担当するため、これは悪い習慣です。詳細については、こちらをご覧ください。

より良い方法は、別のスレッドでこれを行うことです。これは、例えば

  • カスタム ワーカー スレッドまたは
  • AsyncTask。_

の例AsyncTask(これはクラス内に入ります):

public void MakeRequest(View v)
{
    EditText mEdit;
    mEdit = (EditText)findViewById(R.id.editText1);
    new RequestTask().execute(mEdit.getText().toString());
}

private class RequestTask extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... params) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpHead httphead = new HttpHead(params[0]);

        try {
            HttpResponse response = httpClient.execute(httphead);
            return response.toString();
        } catch (ClientProtocolException e) {
            // writing exception to log
            e.printStackTrace();
        } catch (IOException e) {
            // writing exception to log
            e.printStackTrace();
        }
        return "";
    }

    @Override
    protected void onPostExecute(String result) {
        TextView txtresponse;
        txtresponse = (TextView)findViewById(R.id.textView1);
        txtresponse.setText(result);
    }

    @Override
    protected void onPreExecute() {}

    @Override
    protected void onProgressUpdate(Void... values) {}
}
于 2014-01-05T19:17:52.477 に答える