使用Retrofit2向MySQL发送带字符串分类的API请求失败排查
catid Parameter Showing as Null in PHP Let's walk through the most common reasons why your catid parameter is coming up null in your PHP script, even though you're passing it via Retrofit2:
1. Mismatched Parameter Names
This is the #1 culprit. Double-check that the parameter name you're using in Retrofit exactly matches what your PHP script is looking for. For example:
- If your Retrofit interface has:
But your PHP uses@GET("fetch_data.php") Call<DataResponse> getCategoryData(@Query("cat_id") String categoryId);$_GET['catid'], the names don't align (cat_idvscatid)—so PHP will return null. Fix this by making both names identical, like@Query("catid")in Retrofit and$_GET['catid']in PHP.
2. Incorrect HTTP Method or Annotation
Retrofit uses different annotations for different request types, and PHP reads parameters from different superglobals based on the method:
- GET Requests: Use
@Queryin Retrofit, and access the parameter via$_GET['catid']in PHP. - POST Requests: You need to use
@Fieldwith@FormUrlEncoded(for form-data), and access via$_POST['catid']in PHP. Example of correct POST setup:
If you mix these up (e.g., using@FormUrlEncoded @POST("fetch_data.php") Call<DataResponse> getCategoryData(@Field("catid") String categoryId);@Queryfor a POST request, or trying to read$_POSTfor a GET), your parameter will be null.
3. Using Request Body Instead of Form Data
If you're sending a JSON body with @Body in Retrofit, PHP won't find the parameter in $_POST or $_GET—you need to parse the raw request body instead. For example:
- Retrofit code:
@POST("fetch_data.php") Call<DataResponse> getCategoryData(@Body CategoryRequest request); // Where CategoryRequest has a "catid" field - PHP code to parse JSON:
If you forget to do this and still try to use$rawInput = file_get_contents('php://input'); $requestData = json_decode($rawInput, true); $catid = $requestData['catid'] ?? null;$_POST['catid'], it will be null.
4. Case Sensitivity
PHP's $_GET and $_POST arrays are case-sensitive. If your Retrofit code passes CatId but your PHP looks for catid, it will return null. Make sure the capitalization matches exactly on both ends.
5. Test the Request Independently
To rule out PHP-side issues, test your API directly with a tool like Postman or curl:
- For GET:
curl "http://your-server-url/fetch_data.php?catid=your-test-category" - For POST:
curl -X POST -d "catid=your-test-category" http://your-server-url/fetch_data.php
If PHP correctly receives catid this way, the problem is definitely in your Retrofit configuration. If not, check for any PHP code that might be filtering or sanitizing parameters unexpectedly.
内容的提问来源于stack exchange,提问作者user9706969

