2017-02-28 56 views
2

用於這樣的正常工作,我的排球代碼:凌空StringRequest頭塊參數

StringRequest stringRequest = new StringRequest(method, URL, listener, errorListener){ 
    @Override 
    protected Map<String, String> getParams() throws AuthFailureError { 
     //parameters are declared above this part of the code 
     return parameters; 
    } 
}; 

然後我得到了錯誤403從服務器端的PHP文件。人們建議添加頭文件來請求。所以,我在我的代碼改成這樣:

StringRequest stringRequest = new StringRequest(method, URL, listener, errorListener){ 
    @Override 
    protected Map<String, String> getParams() throws AuthFailureError { 
     //parameters are declared above this part of the code 
     return parameters; 
    } 

    @Override 
    public Map<String, String> getHeaders() throws AuthFailureError 
    { 
     Map<String, String> headers = new HashMap<String, String>(); 
     headers.put("Content-Type", "application/form-data; charset=utf-8"); 
     return headers; 
    } 
}; 

添加頭,我能夠擺脫錯誤403之後,但現在凌空沒有通過我的參數給服務器。一切似乎都是空的。

我也嘗試使用getBodyContentType()而不是GetHeaders(),但仍然會出現同樣的問題。

編輯,整個代碼:

public static void execute(final Request request, Context context){ 
    if(queue == null) 
     queue = Volley.newRequestQueue(context); 

    final Map<String, String> parameters = new HashMap<String, String>(); 
    for(int index = 0; index < request.getParameters().length; index++){ 
     parameters.put(request.getParameters()[index].getName(), request.getParameters()[index].getValue()); 
    } 

    int method; 
    switch (request.getRequestType()){ 
     case GET: method = Method.GET; break; 
     case POST: method = Method.POST; break; 
     default: method = Method.POST; break; 
    } 

    String URL = request.getURL(); 

    VolleyRequest newPostRequest = new VolleyRequest 
      (com.android.volley.Request.Method.POST, URL, parameters, new Response.Listener<JSONObject>() { 

       @Override 
       public void onResponse(JSONObject response) { 
        request.onResponse(response.toString()); 

       } 
      }, new Response.ErrorListener() { 

        @Override 
        public void onErrorResponse(VolleyError error) { 
         System.out.println(error.getMessage()); 
         // TODO Auto-generated method stub 

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

        } 

       }; 

    queue.add(newPostRequest); 
} 

服務器端:

<?php 
require_once 'connection.php'; 

$name = $_POST['name']; 
$token = $_POST['token']; 

if(strlen($name) < 4){ 
    $feed = array("Result" => "Failed", "Message" => "Name must be at least four characters!"); 
    echo json_encode($feed); 
    die; 
} 

$sql = $conn->prepare("SELECT name FROM user WHERE name = :name"); 
$sql->bindParam(':name', $name); 
$sql->execute(); 
if($sql->rowCount() > 0){ 
    $feed = array("Result" => "Failed", "Message" => "This name is already taken!"); 
    echo json_encode($feed); 
    die; 
} 
$sql = $conn->prepare("INSERT INTO user (name, device_token) VALUES (:name, :token)"); 
$sql->bindParam(':name', $name); 
$sql->bindParam(':token', $token); 
$sql->execute(); 
$id = $conn->lastInsertId(); 
$feed = array("Result" => "Successful", "ID" => $id); 
echo json_encode($feed); 

?> 
+0

哪種方法您使用的? GET還是POST? –

+0

@AGMTazim我正在使用POST方法。 –

+0

通過返回「application/x-www-form-urlencoded; charset = UTF-8」來嘗試getBodyContentType();和getBody() –

回答

0

按照這種方式。使用此自定義請求類。

public class VolleyRequest extends Request<JSONObject> { 

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

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

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

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



    @Override 
    protected void deliverResponse(JSONObject response) { 
     listener.onResponse(response); 
    } 

    @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)); 
     } 
    } 

} 

並實行這樣的方式 -

Map<String, String> params = new HashMap<String, String>(); 
    params.put("param_1", "value_1"); 
    params.put("param_2", "value_2"); 

    VolleyRequest newPostRequest = new VolleyRequest 
        (Request.Method.POST, url, params, new Response.Listener<JSONObject>() { 

         @Override 
         public void onResponse(JSONObject response) { 
          Log.d(CLASS_NAME, " Response: " + response.toString()); 


        }, new Response.ErrorListener() { 

         @Override 
         public void onErrorResponse(VolleyError error) { 
          // TODO Auto-generated method stub 

         } 
        }){ 
       @Override 
       public Map<String, String> getHeaders() throws AuthFailureError { 
        Map<String, String> headers = new HashMap<String, String>(); 
        headers.put("Content-Type", "application/form-data; charset=utf-8"); 

        return headers; 

       } 

      }; 

Volley.newRequestQueue(context.getApplicationContext()).add(newPostRequest); 

EDIT2:服務器端代碼:

require_once 'connection.php'; 

$name = $_POST['name']; 
$token = $_POST['token']; 

if(strlen($name) < 4){ 
    $feed = array("Result" => "Failed", "Message" => "Name must be at least four characters!"); 
    echo json_encode($feed); 
    die; 
} 

$sql = $conn->prepare("SELECT name FROM user WHERE name = :name"); 
$sql->bindParam(':name', $name); 
$sql->execute(); 
if($sql->rowCount() > 0){ 
    $feed = array("Result" => "Failed", "Message" => "This name is already taken!"); 
    echo json_encode($feed); 
    die; 
} 
$sql = $conn->prepare("INSERT INTO user (name, device_token) VALUES (:name, :token)"); 
$sql->bindParam(':name', $name); 
$sql->bindParam(':token', $token); 
$sql->execute(); 
$id = $conn->lastInsertId(); 
$feed = array("Result" => "Successful", "ID" => $id); 
echo json_encode($feed); 
+0

嘿,謝謝你的答案。然而,它又是一樣的結果。只要我重寫getHeaders(),參數就停止工作。 –

+0

作爲內容類型嘗試使用「application/x-www-form-urlencoded; charset = UTF-8」並查看會發生什麼。 –

+0

仍然一樣。 –