Volley POST 未传递 URL ENCODED 参数

Volley POST with URL ENCODED parameters not being passed

我需要制作一个 HTTPS POST,使用 url 编码参数,如下所示:

https://logintest.moveon.pro/?rest_route=/simple-jwt-login/v1/auth&email=Email&password=Password

然后像这样进入 return JSON :

{"success":false,"data":{"message":"Wrong user credentials.","errorCode":48}}

我在 Android Studio 上使用 Volley 库。

我做了什么:

  1. 我已经在 PostMan 上尝试了完整的流程。这是结论:
  1. 在APP中安装了Volleybuild.gradle build.gradle Volley dependenciy

  2. 已在我的 Manifest.xml 中授权互联网和网络状态 manifest.xml INTERNET & NETWROK STATE

  3. 做了一个非常基本的登录界面作为主界面activity

  4. 点击时,指导我完成我的测试。

这是我执行的 3 个测试:

一个。使用 StringRequest(是的,我想要一个 POST,但在请求 body 中不需要任何内容​​,我认为这可能是一个简单的想法)。我在这里做了很多测试,与下一个主题 JsonObjectRequest 一样。

b。使用 JsonObjectRequest(对这个做了很多尝试!我想我真的尝试了所有我能在 Whosebug 上找到的东西......和其他......)。 除了其他尝试覆盖 BodyContent、Headers、Body 等...

c。使用扩展请求的新“帮助”class。正如我阅读 here.

我的问题是什么:

我找不到将参数传递给 POST url... 调试时我得到 Volley 的“mUrl”作为基本 URL( https://logintest.moveon.pro/) and not the one with added parameters (https://logintest.moveon.pro/?rest_route=/simple-jwt-login/v1/auth&email=Email&password=Password).

这是我的代码... 为了测试不同的方法,我使用了一个愚蠢的“如果”,不要为此责怪我 ;-)... 并且要发送的参数中有很多冗余。

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    /**
     * Logcat tag
     */
    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final EditText usernameEditText = findViewById(R.id.username);
        final EditText passwordEditText = findViewById(R.id.password);
        final Button loginButton = findViewById(R.id.login);
        final ProgressBar loadingProgressBar = findViewById(R.id.loading);

        loginButton.setOnClickListener(new View.OnClickListener() {

            private static final String URL_LOGIN = "http://logintest.moveon.pro";
            //private static final String URL_LOGIN = "http://logintest.moveon.pro/?rest_route=/simple-jwt-login/v1/auth&email=Email&password=Password";
            private static final String route = "/simple-jwt-login/v1/auth";

            @Override
            public void onClick(View v) {

                // Build the request payload -- tried not working better
                final JSONObject jsonObject = new JSONObject();
                try {
                    jsonObject.put("rest_route", "/simple-jwt-login/v1/auth");
                    jsonObject.put("email", "john@domain.com");
                    jsonObject.put("password", "ghjghjk");
                 } catch (JSONException e) {
                    e.printStackTrace();
                }

                // Instantiate the RequestQueue.
                RequestQueue queue = Volley.newRequestQueue(getApplicationContext());

                //Tried different ways of sending the request :
                //String url = "http://logintest.moveon.pro/?rest_route=/simple-jwt-login/v1/auth&email=Email&password=Password";
                //String url = "http://logintest.moveon.pro/wp-json/?rest_route=/simple-jwt-login/v1/auth&email=Email&password=Password";
                String url = "http://logintest.moveon.pro/";

                int test = 3;
                if (test == 0) {
                    // Request a string response from the provided URL.
                    StringRequest sr = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    Log.e("HttpClient", "success! response: " + response.toString());
                                    // Display the first 500 characters of the response string.
                                    usernameEditText.setText("Response is: " + response.toString().substring(0, 500));
                                }
                            },
                            new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError error) {
                                    usernameEditText.setText("That didn't work!");
                                    Log.e("HttpClient", "error: " + error.toString());
                                }
                            }) {
                        @Override
                        protected Map<String, String> getParams() {
                            Map<String, String> params = new HashMap<String, String>();
                            params.put("rest_route", "/simple-jwt-login/v1/auth");
                            params.put("email", "asdasd");
                            params.put("password", "ghjghjk");
                            return params;
                        }

                        //Tried with adding params in Body... but not working better
                        @Override
                        public byte[] getBody() throws AuthFailureError {
                            HashMap<String, String> params2 = new HashMap<String, String>();
                            params2.put("rest_route", "/simple-jwt-login/v1/auth");
                            params2.put("email", "john@domain.com");
                            params2.put("password", "ghjghjk");
                            return new JSONObject(params2).toString().getBytes();
                        }

                        //Tried defining the Body content in different ways... but not working better
                        @Override
                        public String getBodyContentType() {
                            return "application/json; charset=UTF-8";
                        }
                        @Override
                        public Map<String, String> getHeaders() throws AuthFailureError {
                            HashMap<String, String> headers = new HashMap<String, String>();
                            //headers.put("Content-Type", "application/x-www-form-urlencoded;  charset=UTF-8");
                            //headers.put("Content-Type","application/x-www-form-urlencoded");
                            headers.put("Content-Type", "application/json;  charset=UTF-8");
                            return headers;

                        }

                    };
                    // Add the request to the RequestQueue.
                    queue.add(sr);

                } else if (test == 1) {


                    Map<String, String> params = new HashMap<String, String>();
                    params.put("rest_route", "/simple-jwt-login/v1/auth");
                    params.put("email", "asdasd");
                    params.put("password", "ghjghjk");
                    JSONObject parameters = new JSONObject(params);


                    // Request a string response from the provided URL.
                    JsonObjectRequest stringRequest1 = new JsonObjectRequest(Request.Method.POST, url, parameters,
                            new Listener<JSONObject>() {
                                @Override
                                public void onResponse(JSONObject response) {
                                    // Display the first 500 characters of the response string.
                                    usernameEditText.setText("Response is: " + response.toString().substring(0, 500));

                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            usernameEditText.setText("That didn't work!");
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() {
                            Map<String, String> params = new HashMap<String, String>();
                            params.put("rest_route", "/simple-jwt-login/v1/auth");
                            params.put("email", "asdasd");
                            params.put("password", "ghjghjk");
                            return params;
                        }

                        @Override
                        public Map<String, String> getHeaders() throws AuthFailureError {
                            HashMap<String, String> headers = new HashMap<String, String>();
                            headers.put("Content-Type", "application/x-www-form-urlencoded;  charset=UTF-8");
                            //headers.put("Content-Type", "application/json");
                            return headers;

                        }
                    };
                    // Add the request to the RequestQueue.
                    queue.add(stringRequest1);

                } else if (test == 3) {

                    Map<String, String> params = new HashMap();
                    params.put("rest_route", "/simple-jwt-login/v1/auth");
                    params.put("email", "john@domain.com");
                    params.put("password", "ghjghjk");

                    CustomVolleyRequest strReq = new CustomVolleyRequest(Request.Method.POST, url, params, new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            Log.e("HttpClient", "success! response: " + response.toString());
                            // Display the first 500 characters of the response string.
                            usernameEditText.setText("Response is: " + response.toString().substring(0, 500));
                        }
                    },
                            new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError error) {
                                    usernameEditText.setText("That didn't work!");
                                    Log.e("HttpClient", "error: " + error.toString());
                                }
                            }) ;
                }
            }
        });

    }

}

这里还有“帮手”class 我采用了已经提到的post :

package com.example.logintest;

import java.io.UnsupportedEncodingException;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;

public class CustomVolleyRequest extends Request<JSONObject> {

    private Listener<JSONObject> listener;
    private Map<String, String> params;

    public CustomVolleyRequest(String url, Map<String, String> params, Listener<JSONObject> responseListener, ErrorListener errorListener) {
        super(Method.GET, url, errorListener);
        this.listener = responseListener;
        this.params = params;
    }

    public CustomVolleyRequest(int method, String url, Map<String, String> params, Listener<JSONObject> responseListener, ErrorListener errorListener) {
        super(method, url, errorListener);
        this.listener = responseListener;
        this.params = params;
    }

    protected Map<String, String> getParams()
            throws com.android.volley.AuthFailureError {
        return params;
    }


    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers));
            return Response.success(new JSONObject(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }

    @Override
    protected void deliverResponse(JSONObject response) {
        // TODO Auto-generated method stub
        listener.onResponse(response);
    }
}

您可以通过以下方式发送 x-www-form-urlencoded 请求:

  • 请求header:Content-Type:application/x-www-form-urlencoded
  • 请求body:rest_route=/simple-jwt-login/v1/auth&密码=&电子邮件=。 (用正确的凭据替换占位符)。

您可以查看此以供参考:https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST

让我知道你的更新=)

这是我的工作代码。

问题出在 API 中 returning 400 代码,即使语法是正确的。

感谢 POSTMAN,我发现了这一点后,我寻找了一种方法来使用 Volley Error return.[=12 仍然从我的 POST 中获得正文答案=]

我发现这个 post here 我将其添加到我的解决方案“0”中,最大限度地简化了它,结果如下: 包裹 com.example.logintest;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;

import com.android.volley.NetworkResponse;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.ServerError;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.HttpHeaderParser;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

public class MainActivity extends AppCompatActivity {

    /**
     * Logcat tag
     */
    private static final String TAG = MainActivity.class.getSimpleName();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final EditText usernameEditText = findViewById(R.id.username);
        final EditText passwordEditText = findViewById(R.id.password);
        final Button loginButton = findViewById(R.id.login);
        final ProgressBar loadingProgressBar = findViewById(R.id.loading);

        loginButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                // Instantiate the RequestQueue.
                RequestQueue queue = Volley.newRequestQueue(getApplicationContext());

                String url = "https://logintest.moveon.pro/";

                    // Request a string response from the provided URL.
                    StringRequest sr = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    Log.e("HttpClient", "success! response: " + response.toString());
                                    // Display the first 500 characters of the response string.
                                    usernameEditText.setText("Response is: " + response.toString().substring(0, 500));
                                }
                            },
                            new Response.ErrorListener() {
                                @Override
                                public void onErrorResponse(VolleyError error) {
                                    usernameEditText.setText("That didn't work!");
                                    // As of f605da3 the following should work
                                    NetworkResponse response = error.networkResponse;
                                    if (error instanceof ServerError && response != null) {
                                        try {
                                            String res = new String(response.data,
                                                    HttpHeaderParser.parseCharset(response.headers, "utf-8"));
                                            // Now you can use any deserializer to make sense of data
                                            JSONObject obj = new JSONObject(res);
                                            usernameEditText.setText(usernameEditText.getText() + res);
                                        } catch (UnsupportedEncodingException e1) {
                                            // Couldn't properly decode data to string
                                            e1.printStackTrace();
                                        } catch (JSONException e2) {
                                            // returned data is not JSONObject?
                                            e2.printStackTrace();
                                        }
                                    }
                                    Log.e("HttpClient", "error: " + error.toString());
                                }
                            }) {

                        @Override
                        protected Map<String, String> getParams() {
                            Map<String, String> params = new HashMap<String, String>();
                            params.put("rest_route", "/simple-jwt-login/v1/auth");
                            params.put("email", "dummy@gmail.com");
                            params.put("password", "935jIDan^4S@$rAFLw4w@!$Z");
                            return params;
                        }
                    };
                    // Add the request to the RequestQueue.
                    queue.add(sr);
                }
        });
    }
}

希望这会对某人有所帮助...

此致问候,编码愉快!!!