用Java上传Youtube帖子

用Java上传Youtube帖子,java,youtube-api,Java,Youtube Api,帮助:(有人知道如何用Java编写通过Youtube API上传Youtube视频的POST请求吗 描述了所需POST请求的结构 不幸的是,我不能使用Youtube Java客户端库,因为我使用的是不支持它们的Android 我在下面尝试了一些代码,但它不起作用(我得到的错误是conn.getResponseCode()为null) public void videoUpload(){ HttpURLConnection conn=null; //BufferedReader br=null;

帮助:(有人知道如何用Java编写通过Youtube API上传Youtube视频的POST请求吗

描述了所需POST请求的结构

不幸的是,我不能使用Youtube Java客户端库,因为我使用的是不支持它们的Android

我在下面尝试了一些代码,但它不起作用(我得到的错误是conn.getResponseCode()为null)


public void videoUpload(){
HttpURLConnection conn=null;
//BufferedReader br=null;
DataOutputStream dos=null;
InputStream inStream=null;
//InputStream=null;
//OutputStream os=null;
//布尔ret=false;
//字符串StrMessage=“”;
//文件路径
//从videoURI获取文件名
字符串路径=”file:///sdcard/";
字符串existingFileName=“video.3gp”;
文件videoFile=新文件(路径+现有文件名);
//字符串lineEnd=“\r\n”;
字符串双连字符=“--”;
字符串边界=“b93dcbA3”;
字符串ver=“2”;
int字节读取,字节可用,缓冲区大小;
字节[]缓冲区;
int maxBufferSize=1024;
//字符串responseFromServer=“”;
试一试{
FileInputStream FileInputStream=新的FileInputStream(视频文件);
URL=新URL(“http://uploads.gdata.youtube.com/feeds/api/users/[XXXXXXXXX]/上传”);
conn=(HttpURLConnection)url.openConnection();
//允许输入
conn.setDoInput(真);
//允许输出
连接设置输出(真);
//不要使用缓存副本。
conn.SETUSECHACHES(假);
//使用post方法。
conn.setRequestMethod(“POST”);
//conn.setRequestProperty(“连接”、“保持活动”);
conn.setRequestProperty(“主机”,“uploads.gdata.youtube.com”);
conn.setRequestProperty(“授权”、“谷歌登录验证=“+令牌”);
conn.setRequestProperty(“GData版本”,版本号);
conn.setRequestProperty(“X-Gdata-Client”,clientId);
conn.setRequestProperty(“X-GData-Key”,“Key=“+developerKey”);
conn.setRequestProperty(“Slug”,existingFileName);//修复此问题
conn.setRequestProperty(“内容类型”,
“多部分/相关;边界=”+边界);
conn.setRequestProperty(“内容长度”、新长(视频文件//和此
.length()).toString());
conn.setRequestProperty(“连接”、“关闭”);
//这里不需要边界字符串吗?
conn.setRequestProperty(“内容类型”,
“应用程序/atom+xml;字符集=UTF-8”);
//这里呢?
conn.setRequestProperty(“内容类型”、“视频/3gpp”);
conn.setRequestProperty(“内容传输编码”、“二进制”);
dos=新的DataOutputStream(conn.getOutputStream());
write((两个连字符+边界).toString().getBytes());
StringBuilder test_xml=新建StringBuilder();
test_xml.append(“\n”);
test_xml.append(“\n”);
test_xml.append(“\n”);
test_xml.append(“测试视频”);
test_xml.append(“\nTest Video\n\n”);
test_xml.append(“People\n”);
test_xml.append(“\n”);
test_xml.append(“toast,election,wedding\n”);
test_xml.append(“\n”);
test_xml.append(“”);
write(test_xml.toString().getBytes(“UTF-8”);
//System.out.println(test_xml.toString());
write((两个连字符+边界).toString().getBytes());
//创建最大大小的缓冲区
bytesAvailable=fileInputStream.available();
bufferSize=Math.min(字节可用,maxBufferSize);
buffer=新字节[bufferSize];
//读取文件并将其写入表单
bytesRead=fileInputStream.read(缓冲区,0,缓冲区大小);
而(字节读取>0){
//dos.flush();
写入(缓冲区,0,缓冲区大小);
bytesAvailable=fileInputStream.available();
bufferSize=Math.min(字节可用,maxBufferSize);
bytesRead=fileInputStream.read(缓冲区,0,缓冲区大小);
}
//byte[]buf=新字节[2048];//以2k个块进行传输
//int字节读取=0;
//而((bytesRead=fileInputStream.read(buf,0,buf.length))>=
// 0) {
//写(buf,0,字节读);
////dos.flush();
// }
//在文件数据之后发送所需的多部分表单数据
//dos.writeBytes(lineEnd);
//写字节(两个连字符+边界+两个连字符+行结束);
写((两个连字符+边界+两个连字符).toString()
.getBytes());
//合流
fileInputStream.close();
dos.flush();
dos.close();
}捕获(格式错误){
例如printStackTrace();
}捕获(ioe异常ioe){
ioe.printStackTrace();
}
国际响应码;
StringBuilder outputBuilder=新StringBuilder();
试一试{
responseCode=conn.getResponseCode();
if(responseCode==HttpURLConnection.HTTP\u确定){
inStream=conn.getInputStream();
}否则{
inStream=conn.getErrorStream();
}
字符串字符串;
如果(流内!=null){
BufferedReader reader=新的BufferedReader(
新的InputStreamReader(流内);
while(null!=(string=reader.readLine()){
outputBuilder.append(字符串).append(“\n”);
}
}
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}最后{
如果(流内!=null){
试一试{
流内关闭();
}捕获(IOE异常){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}
}
System.out.println(outputBuilder.toString());
Log.d(Log_标记,outputBuilder.toString());
}

我以前使用过Apache文件上载库,它简化了post-re
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());
}