Android Studio中Java无法从PHP获取JSON问题排查
Hey there, let's figure out why your AsyncTask is returning null when fetching from the PHP server—especially since local JSON files work fine. Here are the most common culprits and how to debug them step by step:
The #1 issue here is almost always invalid or malformed JSON coming from your PHP script. Let's check that first:
- Open your PHP endpoint URL directly in a browser. Look closely at what's returned: is it pure JSON, or is there extra stuff like PHP warnings, notices, or HTML error messages mixed in? Even a single stray space or
Notice: Undefined variablewill break JSON parsing. - Fix your PHP script to ensure clean, valid output:
// Temporarily suppress errors for testing (remove in production) error_reporting(0); // Critical: Set the correct content type header header('Content-Type: application/json'); // Your data variable $responseData = array("status" => "success", "data" => "your content"); // Validate JSON encoding $jsonOutput = json_encode($responseData); if ($jsonOutput === false) { // Print encoding errors to debug echo json_last_error_msg(); exit; } echo $jsonOutput; exit; // Ensure no extra code runs after this
Stop trying to parse JSON right away—first capture and log exactly what the server sends back. Modify your AsyncTask to print the raw response string:
@Override protected String doInBackground(Void... params) { String rawResponse = null; try { URL url = new URL("YOUR_PHP_ENDPOINT_URL"); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); // Log the response code first int responseCode = conn.getResponseCode(); Log.d("ServerCheck", "Response Code: " + responseCode); if (responseCode == HttpURLConnection.HTTP_OK) { BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); } rawResponse = sb.toString(); // Log the raw response to see what's coming in Log.d("RawServerResponse", rawResponse); } else { // Don't ignore error responses—log them too! BufferedReader errorReader = new BufferedReader(new InputStreamReader(conn.getErrorStream())); StringBuilder errorSb = new StringBuilder(); String line; while ((line = errorReader.readLine()) != null) { errorSb.append(line); } Log.e("ServerError", errorSb.toString()); } conn.disconnect(); } catch (Exception e) { e.printStackTrace(); } return rawResponse; } @Override protected void onPostExecute(String result) { super.onPostExecute(result); if (result == null) { Log.e("AsyncTaskIssue", "Result is null—network call failed or returned nothing"); return; } // Now try parsing JSON only if we have a valid raw string try { JSONObject json = new JSONObject(result); // Proceed with your logic } catch (JSONException e) { e.printStackTrace(); Log.e("JSONParseError", "Invalid JSON: " + result); } }
This will show you exactly what's coming from the server—if it's not valid JSON, you'll see why immediately.
Don't overlook basic Android setup:
- Make sure you have the internet permission in your
AndroidManifest.xml:<uses-permission android:name="android.permission.INTERNET" /> - If your app targets API 28 or higher, plain HTTP requests (http://) are blocked by default. If your PHP server uses HTTP (not HTTPS), add this to your
<application>tag in the manifest:android:usesCleartextTraffic="true"
Even tiny stray characters in your PHP file can break JSON. Check for:
- Spaces, newlines, or tabs before the
<?phpopening tag - Extra content after the
?>closing tag (you can even omit the closing tag entirely to avoid this) - Included/required files that output anything other than your intended JSON
Once you've worked through these steps, you should be able to pinpoint exactly where the breakdown is. Most of the time, it's either invalid JSON from the server or a network permission/configuration issue on Android.
内容的提问来源于stack exchange,提问作者Zaki Zakaria

