我JSONObject
用来解析下载的内容。尽管解析器适用于大多数 json,但它会为特定文件中的 json 抛出异常。
任何关于为什么抛出异常以及如何修复它的建议将不胜感激。
代码:
@Override
protected String doInBackground(String... urls) {
// params comes from the execute() call: params[0] is the url.
try {
return downloadUrl(urls[0], parseJson);
} catch (IOException e) {
return "Unable to retrieve web page. URL may be invalid.";
}
}
// onPostExecute displays the results of the AsyncTask.
@Override
protected void onPostExecute(String result) {
// The parsed result comes in here
// textView.setText(result);
}
private String downloadUrl(String URLString, boolean parseJSON) throws IOException { // when parsejson is false, xml will be parsed
InputStream is = null;
// Only display the first 500 characters of the retrieved
// web page content.
int len = 50000;
try {
URL url = new URL(URLString);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
if (useUserAuthentication) connection.setRequestProperty ("Authorization", "Basic TjN3czRwcDI0OnJld2R1Y0NvYVF1ZWFyZzk=");
else connection.setRequestProperty("Authorization", userToken);
connection.setDoInput(true);
connection.setRequestMethod(requestType);
connection.setReadTimeout(10000 /* milliseconds */);
connection.setConnectTimeout(15000 /* milliseconds */);
if (postHashMap != null) {
connection.setDoOutput(true);
String query = getQuery(postHashMap);
int contentLength = query.getBytes("UTF-8").length;
connection.setFixedLengthStreamingMode(contentLength);
OutputStream os = connection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.close();
os.close();
}
// Starts the query
connection.connect();
int response = connection.getResponseCode();
Log.i(LOGTAG, "The response is: " + String.valueOf(response));
is = connection.getInputStream();
// Convert the InputStream into a string
String contentAsString = readIt(is, len);
// CREATE IMAGE FROM INPUT STREAM
//Bitmap bitmap = BitmapFactory.decodeStream(is);
//ImageView imageView = (ImageView) findViewById(R.id.image_view);
//imageView.setImageBitmap(bitmap);
if (parseJSON) {
try {
String length = String.valueOf(contentAsString.length());
Log.i(LOGTAG, "the length is " +length);
//contentAsString = "{\"string\":\"But during winter, it’s more important\"}";
//contentAsString.replace("’","'");
//contentAsString = "{\"user_id\":\"juan\"}";
JSONObject jsonObject = new JSONObject(contentAsString);
// New User
if (requestName.equals("NewUser")) {
String tempToken = jsonObject.getString("token");
String tempUserID = jsonObject.getString("user_id");
if (tempToken != null && tempToken.length() > 0) {
userToken = "Token " +tempToken;
Log.i(LOGTAG, "saving the token " +userToken);
SharedPreferences sharedPref = context.getSharedPreferences(context.getString(R.string.app_preferences), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("UserToken", userToken);
editor.putString("UserID", tempUserID);
editor.commit();
// Request content
indexArticlesForCategories();
}
}
// Index articles
else if (requestName.equals("IndexArticlesForCategories")) {
Log.i(LOGTAG,"got here");
}
// User Profile
else if (requestName.equals("UserProfile")) {
Log.i(LOGTAG, "the user id is " +jsonObject.getString("user_id"));
}
}
catch (JSONException e) {
Log.i(LOGTAG, "json exception " +e.getMessage());
e.printStackTrace();
Log.getStackTraceString(e.getCause().getCause());
}
Log.i(LOGTAG, "the json data " + contentAsString);
}
return contentAsString;
// Makes sure that the InputStream is closed after the app is finished using it.
} finally {
if (is != null) {
is.close();
}
}
}
// convert input stream to text
public String readIt(InputStream stream, int len) throws IOException, UnsupportedEncodingException {
// Reader reader = null;
// reader = new InputStreamReader(stream, "UTF-8");
// char[] buffer = new char[len];
// reader.read(buffer);
// return new String(buffer);
BufferedReader reader = new BufferedReader(new InputStreamReader(stream, "UTF-8"));
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
}
return sb.toString();
}
堆栈跟踪(更新):
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:352)
at java.util.concurrent.FutureTask.setException(FutureTask.java:219)
at java.util.concurrent.FutureTask.run(FutureTask.java:239)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1080)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:573)
at java.lang.Thread.run(Thread.java:856)
Caused by: java.lang.NullPointerException
at com.media24.myedit.WebServicesManager$AsyncDownloadTask.downloadUrl(WebServicesManager.java:248)
at com.media24.myedit.WebServicesManager$AsyncDownloadTask.doInBackground(WebServicesManager.java:140)
at com.media24.myedit.WebServicesManager$AsyncDownloadTask.doInBackground(WebServicesManager.java:126)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask.run(FutureTask.java:234)
... 4 more