0
我想打開連接到JSON URL http://www.omdbapi.com/?t=frozen&y=&plot=short&r=json。但我仍然使用下面的代碼爲我的數據檢索-1。我試圖通過使用Log.v
來追蹤我出錯的地方,並且我意識到我實際上是從網站檢索-1,並且循環只運行一次。我究竟做錯了什麼?檢索-1從JSON數據爲不明原因
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字符串?我沒有看到你的代碼 –
是什麼意思......這就是問題 – Jchoi
當你記錄響應代碼時,你看到200嗎? –