-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

它不一定是 AsyncTask,但它必须是主线程(UI 运行的地方)以外的东西。因此,您也可以使用例如线程而不是 AsyncTask。

如果不这样做,4.0 之后的 android 版本将抛出“NetworkOnMainThread”异常。有关更多详细信息,请参阅android 4.0 中主线程异常的网络

于 2013-10-17T05:23:26.340 回答
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 调用不是在主线程上进行的,您应该使用另一个线程来调用长时间运行的操作。

开发者网站中提供了有关异步任务的更多信息

于 2013-10-17T05:27:23.290 回答
0

由于您没有发布任何 logcat,因此很难猜测您的问题。但是在这里,我为您提供了获取 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 回答
0

是的你是对的。您应该使用异步任务从服务器获取数据-

public class getData extends AsyncTask<String, Void, String> {

    ProgressDialog pd = null;

    @Override
    protected void onPreExecute() {
        pd = ProgressDialog.show(LoginPage.this, "Please wait",
                "Loading please wait..", true);
        pd.setCancelable(true);

    }

    @Override
    protected String doInBackground(String... params) {
        try {

            HttpClient client = new DefaultHttpClient();

            HttpGet request = new HttpGet(Constant.URL + "/register.php?name="
                    + userName + "&email=" + userName + "&gcm_regid="
                    + Registration_id);

            HttpResponse response = client.execute(request);
            BufferedReader rd = new BufferedReader(new InputStreamReader(
                    response.getEntity().getContent()));
            System.out.println("***response****" + response);
            String webServiceInfo = "";
            while ((webServiceInfo = rd.readLine()) != null) {
                jsonObj = new JSONObject(webServiceInfo);
                Log.d("****jsonObj", jsonObj.toString());

                break;
            }

        } catch (Exception e) {
            e.printStackTrace();

        }

        return null;
    }

    @Override
    protected void onPostExecute(String result) {
    }
}

现在在你的 onCreate 方法上调用它。

new getData().excute();

谢谢!

于 2013-10-17T05:29:47.620 回答
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 回答