1

私はいくつかのデータをダウンロードするために次の愚かなコードを使用しています:

HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(url));
request.setHeader("User-Agent","Android Browser");
HttpResponse response = client.execute(request);
in=response.getEntity().getContent();
len=(int)response.getEntity().getContentLength();
if (len<=0) return null;
data=new byte[len];
...

この方法でのデータのダウンロードは非常に遅く、接続タイムアウトで失敗することがよくあります。他のユーザーのデバイスでも同じことが起こるので、私のネットワークの構成が理由ではないはずです。

一方、指定された「url」は、通常のブラウザに入力すると正常に機能し、高速で、ほぼ即座に結果を返します。私のAndroidデバイスとそのブラウザを搭載した「通常の」コンピュータは同じWLANネットワーク上で実行されています。では、ここで何が間違っている可能性がありますか?

4

2 に答える 2

0

私にとって、エミュレーターでアプリを実行する(遅い)と電話で実行する(速い)には大きな違いがあります。タイムアウトは、しばらくすると接続を閉じるWebサーバーが原因である可能性があります。ただし、代わりにバッファ付きリーダーを使用してみてください。

    private static JSONArray getJSON(String url) {
    // initialize
    InputStream is = null;
    JSONArray res = null;

    // http post
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();
    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
    }

    // convert response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        res = new JSONArray(sb.toString());
    } catch (Exception e) {
        Log.e("log_tag", "Error converting result " + e.toString());
    }

    return res;
}
于 2012-05-17T15:26:18.443 に答える
0

引用されたコードの外で何か面白いことをしている可能性があります。この関数を実行して、リクエストを完了するのにどのくらいの時間がかかるかをログで確認してください。

function check_fetch_time(String url) {
    long start = System.currentTimeMillis();

    HttpClient client = new DefaultHttpClient();
    HttpGet request = new HttpGet(url);
    HttpResponse response = client.execute(request);
    try {
        flushContent( response.getEntity().getContent() );
    } catch (Exception e) {}

    long elapsed = System.currentTimeMillis() - start;
    Log.v(TAG, "page fetched in " + elapsed + "ms");
}

20秒。はい、実際にはミリ秒ではなく秒です。

まあ、ここで何かが間違いなく正しくありません。携帯電話でブラウザを開いて、ウェブにアクセスしてみてください。ブラウザへのアクセスが同じくらい遅い場合、これはソフトウェアの問題ではありません。おそらく、近所の人がソーセージを電子レンジにかけ、Wi-Fiを妨害している可能性があります。ただし、ブラウザがほぼ瞬時に(1〜2秒以内に)ページを開く場合は、プログラムに何か問題があります。その場合、空のHelloWorldプロジェクトを作成し、check_fetch_time()そこにコピーして再試行します。

于 2012-05-17T15:53:17.493 に答える