PHP POST请求转Android Volley POST请求遇请求为空问题求助
Hey, let's break down why your Volley request is throwing that error and fix it! The root issue is that your Android code isn't matching the exact request format your working PHP code uses.
What's Wrong With Your Current Android Code?
Looking at your PHP code:
- You're sending a form-encoded POST request (content type
application/x-www-form-urlencoded). - The only form parameter is
request, whose value is a URL-encoded JSON string containing your user, auth, and command data.
But your Android code uses JsonObjectRequest, which by default sends a application/json request body (raw JSON directly in the request). Your API expects form data, not raw JSON, so it can't find the request parameter and throws the "empty request" error.
Correct Implementation Step-by-Step
Let's rewrite the code to mimic the PHP request exactly:
1. Add a SHA1 Helper Method
First, replicate the PHP SHA1 hashing logic (your current code has a placeholder for auth):
private String sha1(String input) throws NoSuchAlgorithmException { MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] hashBytes = md.digest(input.getBytes(StandardCharsets.UTF_8)); StringBuilder sb = new StringBuilder(); for (byte b : hashBytes) { sb.append(String.format("%02x", b)); } return sb.toString(); }
2. Full API Call Code
Use StringRequest instead of JsonObjectRequest to send form-encoded data:
String email = "email"; String pass = "password"; // Get Prague local hour (24-hour format) Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("Europe/Prague"), Locale.getDefault()); String hour = String.valueOf(calendar.get(Calendar.HOUR_OF_DAY)); try { // Calculate auth exactly like PHP: sha1(login + sha1(password) + hour) String shaPass = sha1(pass); String auth = sha1(email + shaPass + hour); // Build the inner request JSON object JSONObject requestJson = new JSONObject(); requestJson.put("user", email); requestJson.put("auth", auth); requestJson.put("command", "ping"); // URL-encode the JSON string (matches PHP's urlencode()) String encodedRequest = URLEncoder.encode(requestJson.toString(), "UTF-8"); // Build the form payload: "request=encoded_json_string" String postPayload = "request=" + encodedRequest; // Initialize Volley RequestQueue RequestQueue queue = Volley.newRequestQueue(getContext()); String url = "https://myapi.com/json"; // Create StringRequest for form-encoded POST StringRequest stringRequest = new StringRequest(Request.Method.POST, url, response -> { // Parse the API response try { JSONObject jsonResponse = new JSONObject(response); System.out.println("API Response: " + jsonResponse); } catch (JSONException e) { e.printStackTrace(); } }, error -> Toast.makeText(getContext(), "Error: " + error.getMessage(), Toast.LENGTH_SHORT).show()) { @Override public String getBodyContentType() { // Set correct content type for form data return "application/x-www-form-urlencoded; charset=UTF-8"; } @Override public byte[] getBody() throws AuthFailureError { // Return the form payload as UTF-8 bytes return postPayload.getBytes(StandardCharsets.UTF_8); } }; // Add the request to the queue queue.add(stringRequest); } catch (JSONException | NoSuchAlgorithmException | UnsupportedEncodingException e) { e.printStackTrace(); }
Key Fixes Explained
StringRequestinstead ofJsonObjectRequest: Ensures we send form-encoded data, not raw JSON.- Correct Content-Type: The
getBodyContentType()method sets the same header your PHP curl code uses. - Exact Auth Hashing: We replicate the PHP logic to generate a valid
authvalue (critical for API authentication). - URL-encoded JSON: Matches PHP's
urlencode()call to ensure the JSON is parsed correctly by the API.
内容的提问来源于stack exchange,提问作者Karel Krýda

