Android中如何用Volley发送含必填/可选字段的JSON POST请求
Hey there! Let's adjust your Volley code to only send the required fields (email/phone, at least one) plus any optional fields that have valid, non-empty values. Here's how to do it step by step:
Step 1: Add Validation for Required Fields
First, make sure the user provides at least one of the required fields (email or phone) before sending the request. This prevents unnecessary failed requests to the server.
Step 2: Build JSONObject Conditionally
Instead of adding every field regardless of its value, we'll only add a field to the JSONObject if it has a valid, non-empty value. We'll use TextUtils.isEmpty() to check for empty/null strings, and trim() to remove any leading/trailing whitespace (so we don't send blank strings that might trigger server errors).
Updated sendData() Method
private void sendData() { // 1. Validate required fields first if (TextUtils.isEmpty(user_email) && TextUtils.isEmpty(user_phone)) { Toast.makeText(this, "Please enter either email or phone number", Toast.LENGTH_SHORT).show(); return; // Exit if no required fields are filled } String url = AppConstants.service_url + AppConstants.service_port + AppConstants.rest_service_path + "users/"; final JSONObject jsonObject = new JSONObject(); try { // Add required fields (only if they have values) if (!TextUtils.isEmpty(user_email)) { jsonObject.put("email", user_email.trim()); } if (!TextUtils.isEmpty(user_phone)) { jsonObject.put("phone", user_phone.trim()); } // Add optional fields only if they are not empty if (!TextUtils.isEmpty(user_saluation)) { jsonObject.put("salutation", user_saluation.trim()); } if (!TextUtils.isEmpty(first_name)) { jsonObject.put("firstname", first_name.trim()); } if (!TextUtils.isEmpty(last_name)) { jsonObject.put("lastname", last_name.trim()); } if (!TextUtils.isEmpty(user_address)) { jsonObject.put("address", user_address.trim()); } if (!TextUtils.isEmpty(user_city)) { jsonObject.put("city", user_city.trim()); } if (!TextUtils.isEmpty(user_country)) { jsonObject.put("country", user_country.trim()); } // If zip is optional later, add a check here (e.g., if fetched from input) jsonObject.put("zip", "411001"); // Keep this if it's a fixed required value } catch (JSONException e) { e.printStackTrace(); } // Create and send the Volley request JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, jsonObject, response -> { // Handle successful response here Toast.makeText(this, "Data submitted successfully!", Toast.LENGTH_SHORT).show(); }, error -> { // Handle error response here Toast.makeText(this, "Error submitting data: " + error.getMessage(), Toast.LENGTH_SHORT).show(); }); AppController.getInstance().addToRequestQueue(request, req); }
Button Click Listener (Unchanged)
Your existing click listener works fine—just ensure you're correctly fetching values from your UI elements (e.g., user_email = emailEditText.getText().toString()) before calling sendData():
register.setOnClickListener(v -> sendData());
Key Notes:
TextUtils.isEmpty(): Safely checks for bothnulland empty strings, which is more reliable than just checkinguser_email != "".trim(): Removes accidental leading/trailing spaces, so you don't send blank strings that might fail server validation.- Early Exit: We stop the request immediately if neither email nor phone is provided, saving unnecessary network calls.
This approach ensures your JSONObject only contains the required fields (at least one) and any optional fields with valid values, perfectly matching your server's requirements.
内容的提问来源于stack exchange,提问作者Satyam Gondhale

