2010-02-26 2 views
5

도움말 :(누군가가 자바에서 유튜브 API를 통해 YouTube 동영상을 업로드 POST 요청을 작성하는 방법을 알고 있나요?유튜브 POST

을 필요로하는 POST 요청의 구조는 here을 설명합니다.

자바로 업로드

유감스럽게도 Android 클라이언트에서 지원하지 않는 Youtube Java 클라이언트 라이브러리를 사용할 수 없습니다.

아래에서 시도한 코드가 있지만 작동하지 않습니다. 오류가 발생합니다. conn.getResponseCode()가 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()); 
} 

답변

1

내가 전에 아파치 파일 업로드 라이브러리를 사용했습니다과 크게 등 파일에 대한 POST 요청을 단순화 Apache commons file upload

1

conn.getResponseCode()은 null 일 수 없습니다 원시적 INT를 반환합니다. 내가 무슨 종류의 오류 (NullPointerException?)에 대해 얘기하고 있는지 모르겠지만 getResponseCode가 null을 반환하는 것은 불가능합니다. 아마도 conn 자체가 null입니까?

그렇다면 URL 생성자 또는 url.openConnection()에 의해 다른 예외가 발생했을 수 있습니다. 이 경우 예외를 catch하고 스택 추적을 stdout에 인쇄하지만 잘못된 참조 일 수있는 conn 참조를 계속 사용합니다.