带非密钥对的Android帖子请求

时间:2017-01-01 01:39:19

标签: java android http curl post

以下是我目前正在使用家庭自动化系统打开灯的代码。我正在升级到新系统,它需要一个修改后的命令。目前我认为这会发送密钥对“lightswitch1 = 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

1 个答案:

答案 0 :(得分:0)

以下内容应与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()覆盖,指定的标题覆盖getHeaders()