2014-10-30 287 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; 
}