gpt4 book ai didi

android - Volley StringRequest header block 参数

转载 作者:可可西里 更新时间:2023-11-01 16:40:40 27 4
gpt4 key购买 nike

我的 Volley 代码曾经像这样正常工作:

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

然后我从服务器端的 php 文件中得到错误 403。人们建议在请求中添加 header 。所以我将我的代码更改为:

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

添加 header 后,我能够摆脱错误 403,但现在 Volley 没有将我的参数传递给服务器。一切似乎都是空的。

我也尝试使用 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);

?>

最佳答案

沿着这条路走。使用此自定义请求类。

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

关于android - Volley StringRequest header block 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42508091/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com