以下是我目前使用的代码,用于使用我的家庭自动化系统打开电灯。我正在升级到一个新系统,它需要修改后的命令。目前我认为这会发送 key 对“lightswitch1=ON”。我需要它只发送“ON”,但我不知道该怎么做。下面是有效的 CURL 命令。
public void turnonlight() {
String url = "http://example.com:8090/CMD";
StringRequest MyStringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
//Toast.makeText(MjpegActivity.this,response,Toast.LENGTH_LONG).show();
//This code is executed if the server responds, whether or not the response contains data.
//The String 'response' contains the server's response.
}
},
new Response.ErrorListener() { //Create an error listener to handle errors appropriately.
@Override
public void onErrorResponse(VolleyError error) {
//Toast.makeText(MjpegActivity.this,error.toString(),Toast.LENGTH_LONG).show();
//This code is executed if there is an error.
}
}){
@Override
protected Map<String, String> getParams() {
Map<String, String> MyData = new HashMap<String, String>();
MyData.put(lightswitch1 "ON"); //Add the data you'd like to send to the server.
return MyData;
}
};
RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
MyRequestQueue.add(MyStringRequest);
}
curl -X POST --header "Content-Type: text/plain"--header "Accept: application/json"-d "ON""http://example.com:8090/CMD "
最佳答案
以下应该与 Volley
一起工作:
String url = "http://example.com:8090/CMD";
StringRequest myStringRequest = new StringRequest(Request.Method.POST, url,
new Response.Listener<String>() {
@Override
public void onResponse(String response) {
}
},
new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
}) {
@Override
public Map<String, String> getHeaders() throws AuthFailureError {
Map<String, String> headers = new HashMap<String, String>();
headers.put("Accept", "application/json");
return headers;
}
@Override
public String getBodyContentType() {
return "text/plain";
}
@Override
public byte[] getBody() throws AuthFailureError {
String httpPostBody = "ON";
return httpPostBody.getBytes();
}
};
RequestQueue MyRequestQueue = Volley.newRequestQueue(this);
myStringRequest.setShouldCache(false);
MyRequestQueue.add(myStringRequest);
主体由 getBody()
覆盖,指定的 header 由 getHeaders()
覆盖。
关于java - 具有非 key 对的 Android 发布请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41412806/