2010-02-26 29 views
5

Help :(Có ai biết làm thế nào để viết một yêu cầu POST để tải video Youtube qua API Youtube, trong Java?Youtube POST upload trong Java

Cấu trúc của yêu cầu POST cần được mô tả here.

Thật không may là tôi không thể sử dụng các thư viện máy khách Java của Java, bởi vì tôi đang làm việc trong Android, mà không hỗ trợ chúng. conn.getResponseCode() là null)


public void videoUpload() { 

    HttpURLConnection conn = null; 
    // BufferedReader br = null; 
    DataOutputStream dos = null; 
    InputStream inStream = null; 

    // InputStream is = null; 
    // OutputStream os = null; 
    // boolean ret = false; 
    // String StrMessage = ""; 
    //file path 

    // get filename from videoURI 
    String path = "file:///sdcard/"; 
    String existingFileName = "video.3gp"; 
    File videoFile = new File(path + existingFileName); 

    // String lineEnd = "\r\n"; 
    String twoHyphens = "--"; 
    String boundary = "b93dcbA3"; 
    String ver = "2"; 

    int bytesRead, bytesAvailable, bufferSize; 
    byte[] buffer; 
    int maxBufferSize = 1024; 

    // String responseFromServer = ""; 

    try { 
     FileInputStream fileInputStream = new FileInputStream(videoFile); 

     URL url = new URL("http://uploads.gdata.youtube.com/feeds/api/users/[XXXXXXXXXX]/uploads"); 
     conn = (HttpURLConnection) url.openConnection(); 

     // Allow Inputs 
     conn.setDoInput(true); 
     // Allow Outputs 
     conn.setDoOutput(true); 
     // Don't use a cached copy. 
     conn.setUseCaches(false); 

     // Use a post method. 
     conn.setRequestMethod("POST"); 
     // conn.setRequestProperty("Connection", "Keep-Alive"); 
     conn.setRequestProperty("Host", "uploads.gdata.youtube.com"); 
     conn.setRequestProperty("Authorization", "GoogleLogin auth=" + token); 
     conn.setRequestProperty("GData-Version", ver); 
     conn.setRequestProperty("X-Gdata-Client", clientId); 
     conn.setRequestProperty("X-GData-Key", "key=" + developerKey); 
     conn.setRequestProperty("Slug", existingFileName); //fix this 
     conn.setRequestProperty("Content-Type", 
       "multipart/related;boundary=" + boundary); 
     conn.setRequestProperty("Content-Length", new Long(videoFile //and this 
       .length()).toString()); 
     conn.setRequestProperty("Connection", "close"); 

     //do we not want a boundary string here? 

     conn.setRequestProperty("Content-Type", 
     "application/atom+xml; charset=UTF-8"); 

     //and here? 
     conn.setRequestProperty("Content-Type", "video/3gpp"); 
     conn.setRequestProperty("Content-Transfer-Encoding", "binary"); 

     dos = new DataOutputStream(conn.getOutputStream()); 
     dos.write((twoHyphens + boundary).toString().getBytes()); 

     StringBuilder test_xml = new StringBuilder(); 
     test_xml.append("<?xml version='1.0' encoding='UTF-8'?>\n"); 
     test_xml.append("<entry xmlns=\"http://www.w3.org/2005/Atom\"\n"); 
     test_xml.append("xmlns:media=\"http://search.yahoo.com/mrss/\"\n"); 
     test_xml.append("xmlns:yt=\"http://gdata.youtube.com/schemas/2007\">\n"); 
     test_xml.append("<media:group>\n"); 
     test_xml.append("<media:title type=\"plain\">Test Video</media:title>\n"); 
     test_xml.append("<media:description type=\"plain\">\nTest Video\n</media:description>\n"); 
     test_xml.append("<media:category\n"); 
     test_xml.append("scheme=\"http://gdata.youtube.com/schemas/2007/categories.cat\">People\n"); 
     test_xml.append("</media:category>\n"); 
     test_xml.append("<media:keywords>toast, election, wedding</media:keywords>\n"); 
     test_xml.append("</media:group>\n"); 
     test_xml.append("</entry>"); 

     dos.write(test_xml.toString().getBytes("UTF-8")); 

     // System.out.println(test_xml.toString()); 
     dos.write((twoHyphens + boundary).toString().getBytes()); 

     // create a buffer of maximum size 
     bytesAvailable = fileInputStream.available(); 
     bufferSize = Math.min(bytesAvailable, maxBufferSize); 
     buffer = new byte[bufferSize]; 

     // read file and write it into form 
     bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
     while (bytesRead > 0) { 
      // dos.flush(); 
      dos.write(buffer, 0, bufferSize); 
      bytesAvailable = fileInputStream.available(); 
      bufferSize = Math.min(bytesAvailable, maxBufferSize); 
      bytesRead = fileInputStream.read(buffer, 0, bufferSize); 
     } 

     // byte [] buf = new byte[2048]; // Transfer in 2k chunks 
     // int bytesRead = 0; 
     // while ((bytesRead = fileInputStream.read(buf, 0, buf.length)) >= 
     // 0) { 
     // dos.write(buf, 0, bytesRead); 
     // // dos.flush(); 
     // } 

     // send multipart form data necesssary after file data 
     // dos.writeBytes(lineEnd); 
     // dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); 
     dos.write((twoHyphens + boundary + twoHyphens).toString() 
       .getBytes()); 

     // close streams 
     fileInputStream.close(); 
     dos.flush(); 
     dos.close(); 


    } catch (MalformedURLException ex) { 
     ex.printStackTrace(); 
    } catch (IOException ioe) { 
     ioe.printStackTrace(); 
    } 


    int responseCode; 
    StringBuilder outputBuilder = new StringBuilder(); 
    try { 
     responseCode = conn.getResponseCode(); 
     if (responseCode == HttpURLConnection.HTTP_OK) { 
      inStream = conn.getInputStream(); 
     } else { 
      inStream = conn.getErrorStream(); 
     } 

     String string; 
     if (inStream != null) { 
      BufferedReader reader = new BufferedReader(
        new InputStreamReader(inStream)); 
      while (null != (string = reader.readLine())) { 
       outputBuilder.append(string).append("\n"); 
      } 
     } 
    } catch (IOException e) { 
     // TODO Auto-generated catch block 
     e.printStackTrace(); 
    } finally { 
     if (inStream != null) { 
      try { 
       inStream.close(); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 
     } 
    } 

    System.out.println(outputBuilder.toString()); 
    Log.d(LOG_TAG, outputBuilder.toString()); 
} 

Trả lời

1

Tôi đã sử dụng thư viện tập tin tải lên Apache trước và nó đơn giản hoá bài yêu cầu cho các tập tin vv rất nhiều: Apache commons file upload

1

conn.getResponseCode() trả về một int nguyên thủy, mà không thể được null. Tôi không chắc chắn loại lỗi bạn đang nói về (NullPointerException?), Nhưng nó không phải là có thể getResponseCode trả về null. Có lẽ conn chính nó là null?

Nếu có, ngoại lệ khác có thể được tạo bởi trình tạo URL hoặc bởi url.openConnection(). Trong trường hợp này, bạn đang bắt ngoại lệ và in dấu vết ngăn xếp để stdout, nhưng tiếp tục sử dụng tham chiếu conn, có thể không hợp lệ.