从JSON数据中检索-1,原因不明

时间:2016-03-13 15:52:54

标签: android json

我正在尝试打开与JSON URL http://www.omdbapi.com/?t=frozen&y=&plot=short&r=json的连接。但我使用下面的代码继续检索-1我的数据。我试图通过使用Log.v来追踪我出错的地方,并且我意识到我实际上是从网站上检索-1并且循环只运行一次。我做错了什么?

public class GetRawData {

private String url;
private String mData;
private static final String LOG_TAG = "GetRawData";

public GetRawData(String url) {
    this.url = url;
}

public void execute () {
    GetRawDataBackground getRawDataBackground = new GetRawDataBackground();
    getRawDataBackground.execute(url);
}

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

    private StringBuffer stringBuffer;

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

        mData = processDownloads (params[0]);

        if (mData == null){
            Log.e(LOG_TAG, "Null returned during processing");
            return null;
        }

        Log.v(LOG_TAG, "Data retrieved from doInBackground : " + mData);

        return mData;
    }

    @Override
    protected void onPostExecute(String s) {
        Log.v(LOG_TAG, "Data retrieved is : " + s);
        super.onPostExecute(s);
    }

    private String processDownloads (String mUrl){

        HttpURLConnection connection = null;
        BufferedReader reader = null;

        try {
            if (mUrl == null){
                return null;
            }
            URL url = new URL(mUrl);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            int responseCode = connection.getResponseCode();
            Log.d(LOG_TAG, "Response code is : " + responseCode);

            reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            stringBuffer = new StringBuffer();

            while (reader.readLine() != null){
                stringBuffer.append(reader.read());
                Log.v(LOG_TAG, "while loop " + stringBuffer.toString());
            }

            Log.v(LOG_TAG, "stringBuffer" + stringBuffer.toString());

            return stringBuffer.toString();


        } catch (MalformedURLException e) {
            Log.e(LOG_TAG, "MalformedURLException");
            return null;
        } catch (IOException e){
            Log.e(LOG_TAG, "IOException in making connection");
            return null;
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    Log.e(LOG_TAG, "Error attempting to close reader");
                }
            }
        }


    }
}
}

1 个答案:

答案 0 :(得分:1)

您的问题是您忽略了从BufferedReader

中读取的行

试试这个

StringBuilder sb = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream));
 String line;
 while ((line = rd.readLine()) != null) {
     sb.append(line);
 }
 return sb.toString();