总是意外停止

时间:2013-10-17 05:13:55

标签: android json

    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;

}

我已经用Google搜索了很多从网址获取json字符串,但我认为现在是时候提出这个问题了。几乎所有这个问题的算法都不适合我。它真的需要与AsyncTask一起使用吗?我是android的初学者,所以我不太了解。请帮我。或者,如果您可以提供更好的算法,请执行此操作。

5 个答案:

答案 0 :(得分: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());
}

试试这个

答案 1 :(得分:0)

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

如果不这样,4.0之后的Android版本将抛出“NetworkOnMainThread”异常。 有关详细信息,请参阅Netwok on main thread exception in android 4.0

答案 2 :(得分: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调用,您应该使用另一个线程来调用长时间运行的操作。

有关异步任务的更多信息,请参见developers website

答案 3 :(得分:0)

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

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();

谢谢!

答案 4 :(得分: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;
    }