我知道有类似的问题,但我已经搜索了很多,但它们似乎对我不起作用。所以我想做的是发送一个带有简单字符串 "ON"/"OFF"
作为数据的 post 请求。像这样的东西(对于某些 $URL):
curl -X POST --header "Content-Type: text/plain; charset=utf-8" -d "ON" "$URL"
这是我正在尝试的代码,在阅读了大量代码和此处的答案后,我认为它可以工作,但事实并非如此。
我错过了什么?我从服务器收到 400 错误
。
Request request = new StringRequest
(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Log.d(TAG, "Command was sent successfully");
}},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Got command error for " + url + " command " + command + " error " + error.getMessage());
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Content-Type", "text/plain; charset=utf-8");
// headers.put("Accept", "application/json");
// headers.put("User-agent", "My useragent");
return headers;
}
@Override
public byte[] getBody() throws AuthFailureError {
try {
return command.getBytes("utf-8");
} catch (Exception e) {
Log.d(TAG, "failed converting" + e.getMessage());
return null;
}
}
};
最佳答案
你必须覆盖 getParams()
@Override
protected Map<String, String> getParams() throws com.android.volley.AuthFailureError {
Map<String, String> params = new HashMap<String, String>();
params.put("postData", "my simple on/off string");
return params;
};
关于android - Volley android 库发布请求不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35408272/