我想将POST发送到主体为true或false的服务器。我有这个代码,我使用的是Volley库
ShoozyHeader()将内容类型设置为text / plain,并将Accept设置为text / plain以及身份验证所需的其他标头。
如果我尝试http://requestmaker.com/并且服务器响应正确但我运行此代码服务器响应:
错误请求 - 标头无效 HTTP错误400.请求的标头名称无效。
如果我删除了getBody(),服务器响应正常。
final String url = POSTS_URI + idPost + "/likes";
StringRequest strReq = new StringRequest(Request.Method.POST,
url, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, response);
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
Toast.makeText(act, "Network error", Toast.LENGTH_SHORT).show();
}
}
) {
@Override
public byte[] getBody() throws AuthFailureError {
return "true".getBytes();
}
};
答案 0 :(得分:1)
尝试这个,它对我来说很好:
JSONObject params = new JSONObject();
try {
params.put("likes", "true");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//
JsonObjectRequest jsonObjReq = new JsonObjectRequest(Method.POST,
url, params,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
Log.d(TAG, response.toString());
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d(TAG, "Error: " + error.getMessage());
}
}) {
/**
* Passing some request headers
* */
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
HashMap<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "application/json; charset=utf-8");
return headers;
}
};
jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(60000,
DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
getRequestQueue(jsonObjReq);
答案 1 :(得分:0)
您是否覆盖了扩展请求的类中的getHeaders?
以下是:
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
return headers != null ? headers : super.getHeaders();
}
以下是设置Base64(用户名,密码)标头的示例:
@Override
private HashMap<String, String> getHeaders() {
HashMap<String, String> headers = new HashMap<>();
headers.put("Authorization", getAuthentication("usernameExample", "passwordExample"));
headers.put("Content-Type", "application/json; charset=utf-8");
Log.d(TAG + "");
return headers;
}
private String getAuthentication(String username, String password) {
String credentials = String.format("%s:%s", username, password);
String auth = "Basic " + Base64.encodeToString(credentials.getBytes(), Base64.DEFAULT);
return auth;
}