向服务器发送文本(或字符串)并获得响应

Send a text(or string) to server and get a response

我想制作一个 register/login 应用程序。我找到了一些例子,但其中大部分对我不起作用。所以我会一步一步做每件事。因此,首先对于登录,我想向服务器发送用户的用户名和密码。所以这里一切正常,但如您所见,我没有向服务器发送任何内容。那么,在哪里以及如何将 "username" 和 "password" 发送到服务器。

private void userLogin() {
    username = usernameField.getText().toString().trim();
    password = passwordField.getText().toString().trim();

    RequestQueue queue = Volley.newRequestQueue(this);

  // Request a string response from the provided URL.
    StringRequest stringRequest = new StringRequest(Request.Method.GET, LOGIN_URL,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Toast toast = Toast.makeText(getApplicationContext(), (response), Toast.LENGTH_SHORT);
                    toast.show();
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast toast = Toast.makeText(getApplicationContext(), "Anything doesn't work!", Toast.LENGTH_SHORT);
            toast.show();
        }
    });
 // Add the request to the RequestQueue.
    queue.add(stringRequest);
}

如果您的请求是 GET 请求,请尝试以下 got。

private void userLogin() {
    username = usernameField.getText().toString().trim();
    password = passwordField.getText().toString().trim();

    RequestQueue queue = Volley.newRequestQueue(this);

  // Request a string response from the provided URL.
    StringRequest stringRequest = new StringRequest(Request.Method.GET, LOGIN_URL+"?username="+username+"&password="+password, // here you have to add parameters of webservice
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Toast toast = Toast.makeText(getApplicationContext(), (response), Toast.LENGTH_SHORT);
                    toast.show();
                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast toast = Toast.makeText(getApplicationContext(), "Anything doesn't work!", Toast.LENGTH_SHORT);
            toast.show();
        }
    });
 // Add the request to the RequestQueue.
    queue.add(stringRequest);
}

您不能使用 GET 请求 HTTP 正文发送数据。

为此,您使用 POST 请求。

然后,查看其他 StringRequest 构造函数,其中包含 (method, url, onSuccess, onFailure) 的参数超过 4 个的构造函数。

或者...我假设您正在使用 JSON REST API,因此您需要 JSONObjectRequest

从技术上讲,并不禁止在 get 请求中使用 body。

然而,这是一个非常糟糕的主意。 (更多信息在这里:)

这就是为什么许多 http API 不允许您这样做的原因。