2014-10-30 301 views
1

因此,我最近將Volley API集成到了我的應用中以提供雲存儲解決方案(REST)。因爲,在嘗試通過HTTP POST發送RDF(文本/海龜)數據之前,我從來沒有使用API​​。由於我發送GET和POST請求(通過Postman Chrome應用程序),每當我收到200和201響應時,REST服務器都能正常工作。雖然我設法通過API發送一個簡單的GET請求,但是當我發送HTTP POST時,發生了400錯誤。使用Google volley API發送RDF數據的HTTP POST請求

的代碼如下:

//the RDF turtle payload to send over HTTP POST 
final String bodyPost = "@prefix : <http://xxx.xxx.xxx.gr/xxx/schema/xxx#> ." + "\n" + 
        "@prefix xsd: <http://www.w3.org/2001/XMLSchema#> ." + "\n" + 
        "[a :Patient ;" + "\n" + 
        ":lastName "+'"'+"Aylakiotis"+'"'+"^^xsd:string ; " + "\n" + 
        ":firstName "+'"'+"Yiannis"+'"'+"^^xsd:string ;" + "\n" + 
        ":dateOfBirth "+'"'+"1970-04-14"+'"'+"^^xsd:date ;" + "\n" + 
        ":amka "+'"'+"12345678903"+'"'+"^^xsd:string ;" + "\n" + 
        ":gender :Male ;" + "\n" + 
        "] ."; 
RequestQueue queue = Volley.newRequestQueue(this); 
final String URL ="http://xxx.xxx.xxx:8080/xxx/"; 
EditText folderTitle = (EditText) findViewById(R.id.folderTitle); 
StringRequest strReq = new StringRequest(Request.Method.POST, URL, 
      new Response.Listener() { 

       @Override 
       public void onResponse(Object response) { 
        folderTitle.setText("Response is: " + response.toString().substring(0,500)); 

       } 

      }, new Response.ErrorListener() { 
       @Override 
       public void onErrorResponse(VolleyError error) { 
        folderTitle.setText("Error: " + error.getMessage()); 
       } 
      }) { 



     @Override 
     public byte[] getBody() throws AuthFailureError { 
      System.out.println("string post data: " + bodyPost); 
      if (params != null && params.size() > 0) { 
       System.out.println("string post data: " + bodyPost); 
       return encodeParameters(params, getParamsEncoding()); 
      } 
      return bodyPost.getBytes(); 
     } 

     @Override 
     public Map<String, String> getHeaders() throws AuthFailureError { 
      Map<String, String> headers = new HashMap<String, String>(); 
      String creds = String.format("%s:%s", "xxx", "xxx"); 
      String auth = "Basic " + Base64.encodeToString(creds.getBytes(), Base64.DEFAULT); 
      headers.put("Authorization", auth); 
      headers.put("Content-Type", "text/turtle"); 
      return headers; 
     } 

    }; 

    // Add the request to the RequestQueue. 
    queue.add(strReq); 

String bodyPost是數據的有效載荷,我想在一個龜RDF格式發送。我把這個放在我的getBody()方法中,但是我仍然收到了400個錯誤的請求。我已經通過Postman Chrome應用程序通過POST http發送了此字符串,並且它可以工作(201 Created)。我看到大多數實現都有getParams(),但是這需要鍵/值對,而我正在使用三元組,我想整個發送一串原始數據。

回答

0

將您的內容類型設置爲文本/烏龜。覆蓋您的請求標題,如下所示:

@Override 
public Map<String, String> getHeaders() throws AuthFailureError { 
    final HashMap<String, String> params = new HashMap<String, String>(); 
    params.put("Content-Type", "text/turtle"); 
    return params; 
}