2017-01-01 21 views
1

下面是我目前使用我的家庭自動化系統開啓燈的工作代碼。我正在升級到一個新的系統,它需要一個修改後的命令。目前我認爲這發送密鑰對「lightswitch1 = ON」。我需要它只發送「開」,但我不知道如何做到這一點。以下是可用的CURL命令。帶有非密鑰對的Android發佈請求

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

捲曲-X POST --header 「的Content-Type:text/plain的」 --header 「接受:應用/ JSON的」 -d 「ON」, 「http://example.com:8090/CMD

回答

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()指定的頭。

+0

嘗試使用您的代碼發送時出現「BasicNetwork.performRequest:意外的響應代碼400」錯誤。我使用了電線鯊魚,並嗅出了工作要求和非工作要求。右邊的是有效的,左邊的是無效的。我可以改變什麼來使左邊的一個像右邊的那個一樣? –

+0

http://imgur.com/a/e6qvy –

+0

我認爲這是因爲內容類型錯了。 –