2015-10-10 10 views
0

我想在parse.com上將文件上傳到類myclass。現在,當我使用URL作爲https://api.parse.com/1/files/hello時,我得到響應消息Created以及文件在標題中的位置。但是,當我嘗試將其上傳到班級時,我收到了回覆消息: - 錯誤的請求,並且標題表示它是400 request。我究竟做錯了什麼?使用REST java解析上傳到一個類

String name = "file.txt"; 
    URL url = new URL("https://api.parse.com/1/classes/myclass/hello"); 
    HttpURLConnection httpConn = (HttpURLConnection) url.openConnection(); 

    httpConn.setDoOutput(true); 
    httpConn.setRequestMethod("POST"); 
    httpConn.setRequestProperty("X-Parse-Application-Id", "App_Id"); 
    httpConn.setRequestProperty("X-Parse-REST-API-Key", "APp_KeY"); 
    httpConn.setRequestProperty("Content-type", "text/plain"); 
    OutputStream outputStream = httpConn.getOutputStream(); 
    File uploadFile = new File("F:\\file.txt"); 
    InputStream inputStream = new FileInputStream(uploadFile); 
    byte[] buffer = new byte[4096]; 
    int bytesRead = -1; 
    while ((bytesRead = inputStream.read(buffer)) != -1) { 
     outputStream.write(buffer, 0, bytesRead); 
    } 
    outputStream.close(); 
    inputStream.close(); 
    System.out.println("Response message : " + httpConn.getResponseMessage()); 

回答

0

我猜你不能上傳你的班級名稱。我所做的是首先上傳文件,然後將其插入課程中。因爲您使用過Java,所以我將使用Java。因此,首先使用https://api.parse.com/1/files/hello上傳您的文件。
然後你會在收到的頭文件中得到文件的位置。你可以使用httpConn.getResponseHeader("Location");
現在,這會給你的文件的整個網址。但你只需要這個名字。您可以通過以下代碼提取它: -

String ar[] = location.split("[/]"); 
String name = ar[ar.length - 1]; 

現在,將其插入您的班級。但是在插入之前,您必須確保您的班級中的數據類型爲File。現在,使用以下代碼將其插入您的班級: -

httpConn.setDoOutput(true); 
httpConn.setRequestMethod("POST"); 
httpConn.setRequestProperty("X-Parse-Application-Id", "App_Id"); 
httpConn.setRequestProperty("X-Parse-REST-API-Key", "APp_KeY"); 
httpConn.setRequestProperty("Content-type", "application/json"); 
String json = "{\"myclass\":" 
      + "{ " 
      + "\"name\":\"" + name + "\"," 
      + "\"__type\": \"File\"" 
      + "}" 
      + "}"; 
httpConn.getOutputStream().write(json.getBytes()); 

因此,您必須提出總共2個請求。