You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中String无法转为JSONObject异常排查及数据传输方案咨询

Hey there! Let's dig into your problem and figure out what's going on, plus some fixes and alternatives.

1. Why you're getting that ValueException when converting String to JSONObject

Even if your PHP file runs "fine", the issue almost always boils down to the response your Android app is receiving isn't valid JSON. Here are the most likely culprits:

  • Your PHP script is outputting extra content: Maybe there's a stray echo statement, a PHP warning/notice, or even whitespace before/after your echo json_encode(...) call. All of these will make the response string invalid JSON.
  • The URL parameter separator is wrong: In your code, you used & instead of plain & to separate email and password. That's an HTML entity, so PHP will receive a malformed parameter string (like email=xxx&password=yyy instead of two separate parameters) — which probably makes your PHP return an error message instead of the expected JSON.
  • Incomplete or garbled response: If you're not reading the full HTTP response body, the resulting string will be cut off and can't be parsed into a JSONObject.
2. Is OutputStream causing issues?

From the code snippet you shared, we don't see the full OutputStream implementation, but here are common pitfalls if you're using HttpURLConnection to send POST data:

  • Forgetting to set the correct request headers: You need to add Content-Type: application/x-www-form-urlencoded so PHP knows how to parse the POST data.
  • Not properly writing/flushing/closing the OutputStream: If you don't write the full parameter string, or don't flush the stream before reading the response, the request might be incomplete.
  • Not reading the entire response: Using a simple InputStream.read() might not get all the data — always use a BufferedReader to read line-by-line until the end.
3. Better alternatives for passing/fetching data

Writing raw HttpURLConnection code is error-prone. Here are two much cleaner options:

Option 1: OkHttp (simple, robust HTTP client)

This library handles most of the low-level stuff for you, like parameter encoding and response parsing. Here's a quick example:

@Override
protected String doInBackground(String... params) {
    String email = params[0];
    String password = params[1];
    OkHttpClient client = new OkHttpClient();

    // Build the form parameters correctly
    RequestBody formBody = new FormBody.Builder()
            .add("email", email)
            .add("password", password)
            .build();

    Request request = new Request.Builder()
            .url("http://10.0.3.2/magasin/login.php")
            .post(formBody)
            .build();

    try (Response response = client.newCall(request).execute()) {
        if (!response.isSuccessful()) throw new IOException("Unexpected code " + response);
        
        String responseData = response.body().string();
        // Now safely parse to JSONObject
        JSONObject jsonObject = new JSONObject(responseData);
        // Handle your JSON data here
        return responseData;
    } catch (IOException | JSONException e) {
        e.printStackTrace();
        return null;
    }
}

Option 2: Retrofit (for structured REST APIs)

If your project has multiple API calls, Retrofit is even better — it uses annotations to define API endpoints and automatically parses JSON into Java objects. But for a simple login request, OkHttp is more than enough.

Fixing your existing HttpURLConnection code

If you want to stick with what you have, here's the corrected version:

@Override
protected String doInBackground(String... params) {
    String email = params[0];
    String password = params[1];
    String data = "";
    try {
        URL url = new URL("http://10.0.3.2/magasin/login.php");
        // Fix the separator to &, and URL-encode parameters to handle special characters
        String urlParams = "email=" + URLEncoder.encode(email, "UTF-8") 
                + "&password=" + URLEncoder.encode(password, "UTF-8");

        HttpURLConnection httpURLConn = (HttpURLConnection) url.openConnection();
        httpURLConn.setRequestMethod("POST");
        httpURLConn.setDoOutput(true);
        // Set the correct content type header
        httpURLConn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        httpURLConn.setRequestProperty("Content-Length", String.valueOf(urlParams.getBytes().length));

        // Write parameters to OutputStream properly
        OutputStream os = httpURLConn.getOutputStream();
        os.write(urlParams.getBytes());
        os.flush();
        os.close();

        // Read the full response body
        BufferedReader br = new BufferedReader(new InputStreamReader(httpURLConn.getInputStream()));
        StringBuilder sb = new StringBuilder();
        String line;
        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        br.close();
        data = sb.toString();

        // Now try parsing to JSONObject
        JSONObject json = new JSONObject(data);

    } catch (Exception e) {
        e.printStackTrace();
    }
    return data;
}
Quick debugging tips
  • Test your PHP endpoint directly: Use Postman or your browser to send a POST request with the email and password parameters. Check if the response is pure, valid JSON (no extra text, warnings, or whitespace).
  • Enable PHP error logging: Check your server's PHP error log to see if there are hidden errors that are being outputted with your JSON response.
  • Log the response string in Android: Before trying to parse it, log data to Logcat — this will show you exactly what the app is receiving, which is often the key to finding the issue.

内容的提问来源于stack exchange,提问作者Med yacine

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 07:32:13