WebView Post请求JSON参数异常,API获取param值为null求助
Let's figure out why your API is returning null for the "param" key—your current setup has a few common issues that are almost certainly causing this problem:
Incorrect request data format for
application/x-www-form-urlencoded
Most APIs that handle form data rely on theapplication/x-www-form-urlencodedformat, which uses=to separate keys from values. Right now, your data string starts withparam:instead ofparam=—the colon isn't a valid separator for this format, so the server can't link your JSON content to the "param" key, hence it returns null.Unencoded JSON content
Even if you fix the=separator, the JSON string you're passing has newlines and special characters (like double quotes) that need to be URL-encoded. Without encoding, the server's parser will misinterpret these characters, leading to incomplete or invalid data for the "param" field. You should useURLEncoder.encode()on your JSON string before appending it toparam=.Here's a corrected code example:
// First build your JSON without unnecessary newlines String jsonData = "{\"dataFile\": {\"user\": \"asdasdasd\", \"pwd\":\"vasdadsda\", \"email\": \"vasdasdasd@gg.com\"}}"; // Encode the JSON to handle special characters String encodedJson = URLEncoder.encode(jsonData, StandardCharsets.UTF_8.toString()); // Format the data correctly as key=value String data = "param=" + encodedJson; // Send the POST request myWebView.postUrl("url.com", data.getBytes());Missing or incorrect Content-Type header
TheWebView.postUrl()method might not set the correctContent-Typeheader by default. If your API expectsapplication/x-www-form-urlencoded, you need to ensure the request includes this header. A reliable way to do this is usingWebView.loadUrl()with custom headers instead:String jsonData = "{\"dataFile\": {\"user\": \"asdasdasd\", \"pwd\":\"vasdadsda\", \"email\": \"vasdasdasd@gg.com\"}}"; String encodedJson = URLEncoder.encode(jsonData, StandardCharsets.UTF_8.toString()); String postData = "param=" + encodedJson; Map<String, String> headers = new HashMap<>(); headers.put("Content-Type", "application/x-www-form-urlencoded"); myWebView.loadUrl("url.com", headers, postData.getBytes(StandardCharsets.UTF_8));Unnecessary newlines in JSON
While your JSON structure is technically correct, the newlines you added during string concatenation might cause parsing issues on some servers. Stripping those extra newlines simplifies the data and reduces the chance of unexpected parsing errors.
内容的提问来源于stack exchange,提问作者user9985168

