-1
    public JSONObject getJSONFromUrl(String url) {
    InputStream is = null;
    JSONObject jObj = null;
    String json = "";

    try {
        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(url);

        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        is = httpEntity.getContent();           

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    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();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

URLからjson文字列を取得することをたくさんグーグルで検索しましたが、この質問をする時が来たと思います。この問題のほとんどすべてのアルゴリズムが機能していません。本当に AsyncTask で使用する必要がありますか? android初心者なのでよくわかりません。私を助けてください。または、より良いアルゴリズムを提供できる場合は、そうしてください。

4

5 に答える 5

0

サーバーに何かを投稿していない限り、間違っているHttpPost メソッドを呼び出してサーバーに応答を要求していると思います。代わりに、 HttpGetメソッドを呼び出して、このようなサーバーから何かを取得する必要があります

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(url);
        httpGet.setHeader("Accept", "application/json");
        httpGet.setHeader("Content-Type", "application/json");
        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        String ss = EntityUtils.toString(httpEntity);
        System.out.println("response" + ss);

はいWeb サービスを呼び出すときは非同期タスクを使用する必要があります。HTTP 呼び出しはメイン スレッドでは行われないため、実行時間の長い操作を呼び出すには別のスレッドを使用する必要があります。

非同期タスクの詳細については、開発者の Web サイトを参照してください。

于 2013-10-17T05:27:23.290 に答える
0

このように BufferedReader オブジェクトを使用して読み取る

try {
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line); // Don't use \n this will make your json object invalid
    }
    is.close();
    json = sb.toString();
} catch (Exception e) {
    Log.e("Buffer Error", "Error converting result " + e.toString());
}

これを試して

于 2013-10-17T05:17:18.420 に答える
0

AsyncTask である必要はありませんが、メイン スレッド (UI が実行される場所) 以外のものである必要があります。したがって、AsyncTask の代わりにスレッドなどを使用することもできます。

そうしないと、Android 4.0 以降のバージョンで「NetworkOnMainThread」例外がスローされます。詳細については、Android 4.0のメイン スレッド例外でのネットワークを参照してください。

于 2013-10-17T05:23:26.340 に答える
0

logcat を投稿していないため、問題を推測するのは非常に困難です。しかし、ここでは、アプリケーションの 1 つで使用し、スムーズに動作する JSON 応答を取得するためのコードを提供しています。それがあなたにとってもうまくいくことを願っています。

public static String parseJSON(String p_url) {
        JSONObject jsonObject = null;
        String json = null;
        try {
            // Create a new HTTP Client
            DefaultHttpClient defaultClient = new DefaultHttpClient();
            // Setup the get request
            HttpGet httpGetRequest = new HttpGet(PeakAboo.BaseUrl + p_url);
            System.out.println("Request URL--->" + PeakAboo.BaseUrl + p_url);
            // Execute the request in the client
            HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
            // Grab the response
            BufferedReader reader = new BufferedReader(new InputStreamReader(
                    httpResponse.getEntity().getContent(), "UTF-8"));
            json = reader.readLine();
            System.err.println("JSON Response--->" + json);
            // Instantiate a JSON object from the request response
            jsonObject = new JSONObject(json);

        } catch (Exception e) {
            // In your production code handle any errors and catch the
            // individual exceptions
            e.printStackTrace();
        }
        return jsonObject;
    }
于 2013-10-17T05:33:38.267 に答える