【问题标题】:android studio post request volley not returning searchandroid studio发布请求截击不返回搜索
【发布时间】:2016-07-19 05:54:13
【问题描述】:

我正在我的数据库中搜索音乐,我在 swift ios 中也做过同样的事情,没有任何麻烦。但是,当我在 java 中尝试相同的操作时,我只是得到了我的完整表,而不仅仅是我正在搜索的曲目。我对android studio和java很陌生。我正在使用凌空抽射,但我找不到问题。似乎事情没有得到正确发布或被 php 纠正。真正让我感到困惑的是,当我尝试在浏览器中查询数据库时,我也得到了一个错误的输出。当我尝试从 ios 应用程序执行此操作时,我得到了正确的输出,并且它已正确搜索数据库。

这是我的安卓代码

private void searchsong() {

        String submitUrl = SEARCH_SONG_URL+"?searchWord="+searchWord;

        Log.d("search song Json url", submitUrl);

        JsonArrayRequest req2 = new JsonArrayRequest(Request.Method.POST, submitUrl,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());

                            // update the data in your custom method.
                            mJSONAdapter.updateData(response);

                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                VolleyLog.d(TAG, "Error: " + error.getMessage());
                Toast.makeText(getApplicationContext(),
                        error.getMessage(), Toast.LENGTH_SHORT).show();

            }
        }){

            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();

                    Log.d("Submitting searchword", searchWord);

                    params.put("searchWord", searchWord);

                Log.v("Params", "" + params);

                return params;


            }

        };

        // Adding request to request queue
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        requestQueue.add(req2);
    } 

以下是我正在使用的 php 代码。这很容易。当我用 S_post 标签包装时它也不起作用

<?php
header('Content-type: application/json');
//if($_POST) {


    $searchWord = $_POST['searchWord']; 


  //open connection to mysql db
    $connection = mysqli_connect("$host","$db_user","$db_password","$db_name") or die("Error " . mysqli_error($connection));

    //fetch table rows from mysql db
    $sql = 'SELECT * FROM tracks WHERE track_name LIKE "' . $searchWord . '%"' . 'OR artist LIKE "% ' . $searchWord . '%"'. 'OR tags LIKE "% ' . $searchWord . '%"'; 
    $result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));

    //create an array

    $emparray = array();
    while($row =mysqli_fetch_assoc($result))
    {
        $emparray[] = $row;
    }

    echo json_encode($emparray);

    //close the db connection
    mysqli_close($connection);


//}/*end if POST*/

?>

似乎我的 android 代码没有发布到 php 文件,但是当我查看 logcat 时,它显示了一个 url,上面写着 php?searchWord=..... 我完全不知道我做错了什么.我已经构建了一个登录脚本来检查用户凭据,它工作得很好。我很困惑为什么这不起作用。

感谢您的帮助

【问题讨论】:

    标签: java php json post android-studio


    【解决方案1】:

    您不会按预期发送帖子参数。 2个解决方案:

    1) 将请求改为GET

    这里

    JsonArrayRequest req2 = new JsonArrayRequest(Request.Method.POST, 提交网址,

    这里

    $searchWord = $_POST['searchWord'];

    你可以删除这个:

    > @Override
    >             protected Map<String, String> getParams() {
    >                 Map<String, String> params = new HashMap<String, String>();
    > 
    >                     Log.d("Submitting searchword", searchWord);
    > 
    >                     params.put("searchWord", searchWord);
    > 
    >                 Log.v("Params", "" + params);
    > 
    >                 return params;
    > 
    > 
    >             }
    

    选项 2:使用 POST 但作为 application/x-www-form-urlencoded 发送

    在您的请求中覆盖它:

      public String getBodyContentType() {
            return "application/x-www-form-urlencoded; charset=" + getParamsEncoding();
        }
        /**
         * Returns the raw POST or PUT body to be sent.
         *
         * <p>By default, the body consists of the request parameters in
         * application/x-www-form-urlencoded format. When overriding this method, consider overriding
         * {@link #getBodyContentType()} as well to match the new body format.
         *
         * @throws AuthFailureError in the event of auth failure
         */
        public byte[] getBody() throws AuthFailureError {
            Map<String, String> params = getParams();
            if (params != null && params.size() > 0) {
                return encodeParameters(params, getParamsEncoding());
            }
            return null;
        }
        /**
         * Converts <code>params</code> into an application/x-www-form-urlencoded encoded string.
         */
        private byte[] encodeParameters(Map<String, String> params, String paramsEncoding) {
            StringBuilder encodedParams = new StringBuilder();
            try {
                for (Map.Entry<String, String> entry : params.entrySet()) {
                    encodedParams.append(URLEncoder.encode(entry.getKey(), paramsEncoding));
                    encodedParams.append('=');
                    encodedParams.append(URLEncoder.encode(entry.getValue(), paramsEncoding));
                    encodedParams.append('&');
                }
                return encodedParams.toString().getBytes(paramsEncoding);
            } catch (UnsupportedEncodingException uee) {
                throw new RuntimeException("Encoding not supported: " + paramsEncoding, uee);
            }
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多