Android SDK 28下JSON转换报错求助:数据获取与存储问题
Hey there! Let's troubleshoot the error you're hitting while fetching data and storing it as JSON with your HttpClient code. First off, let's break down the common issues with your current implementation and how to fix them:
First, a quick heads-up: DefaultHttpClient has been deprecated since Apache HttpClient 4.3.x (and Android API 22) — using outdated libraries is a frequent source of unexpected bugs. But let's walk through the most likely problems and solutions:
Common Issues & Fixes
1. Missing Error Handling & Resource Leaks
Your current code doesn't include try-catch blocks or stream cleanup, which can lead to unhandled exceptions (like connection failures, invalid URLs) and resource leaks. Here's how to add proper safety:
InputStream linkinStream = null; try { DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(url); HttpResponse httpResponse = httpClient.execute(httpGet); // Validate the response status first int statusCode = httpResponse.getStatusLine().getStatusCode(); if (statusCode >= 200 && statusCode < 300) { HttpEntity httpEntity = httpResponse.getEntity(); linkinStream = httpEntity.getContent(); // Convert the stream to a JSON string for storage BufferedReader reader = new BufferedReader(new InputStreamReader(linkinStream)); StringBuilder jsonBuilder = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { jsonBuilder.append(line); } String jsonData = jsonBuilder.toString(); // Now you can store jsonData (e.g., to a file, SharedPreferences) } else { throw new IOException("Request failed with status code: " + statusCode); } } catch (IOException e) { e.printStackTrace(); // Add user-facing error handling here (e.g., show a toast/log the issue) } finally { // Clean up the stream to avoid resource leaks if (linkinStream != null) { try { linkinStream.close(); } catch (IOException e) { e.printStackTrace(); } } }
2. Network Operations on Main Thread (Android Context)
If you're running this on Android, executing network calls on the main UI thread will throw a NetworkOnMainThreadException. You need to run the code on a background thread — here's a quick example with an executor:
// Run network code on a background thread ExecutorService executor = Executors.newSingleThreadExecutor(); executor.execute(() -> { // Paste the try-catch code block from above here // After fetching JSON, use runOnUiThread to update UI if needed runOnUiThread(() -> { // Update UI or trigger storage completion }); }); executor.shutdown();
3. Outdated HttpClient Library
Since DefaultHttpClient is deprecated, it's better to switch to a modern alternative like OkHttp (recommended) or the built-in HttpURLConnection. Here's a simplified OkHttp example:
// Add OkHttp dependency first (e.g., implementation 'com.squareup.okhttp3:okhttp:4.11.0') OkHttpClient client = new OkHttpClient(); Request request = new Request.Builder() .url(url) .build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) throw new IOException("Unexpected response: " + response); String jsonData = response.body().string(); // Store jsonData as needed } catch (IOException e) { e.printStackTrace(); }
4. Missing Permissions (Android)
Don't forget to add internet permissions to your AndroidManifest.xml — without these, your app can't make network calls at all:
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Next Steps
If you're still hitting errors, share the exact exception message (from logcat or your console) and details about how you're trying to store the JSON — that will help narrow down the issue even further!
内容的提问来源于stack exchange,提问作者Gunjeet Bawa

