Thursday, January 19, 2012

[YouTube-API] upload using OAuth2 and java client lib

I'm attempting to do a direct upload using OAuth2 and the java client libs, but I'm repeatedly told "Invalid developer key", despite the fact that the developer key I'm using is the one that's shown in my dashboard.

I'm getting an OAuth2 bearer token using cURL (for now; this will be coded later) and then calling

service.setHeader("Authorization", "Bearer " + accessToken);

This same access token works fine in the OAuth2 playground, so it seems to be fine.

Does anybody have a working sample of uploading using the java client libs with OAuth2? Any hints about what might be causing this error?

Here's the code. The YouTubeUpload class is just a POJO that holds video metadata; nothing special there:

package com.contour.share;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.log4j.ConsoleAppender;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.log4j.PatternLayout;
import org.codehaus.jackson.map.ObjectMapper;
import org.scribe.builder.ServiceBuilder;
import org.scribe.builder.api.GoogleApi;
import org.scribe.oauth.OAuthService;

import com.google.gdata.client.Service.GDataRequest;
import com.google.gdata.client.youtube.YouTubeService;
import com.google.gdata.data.media.MediaFileSource;
import com.google.gdata.data.media.mediarss.MediaCategory;
import com.google.gdata.data.media.mediarss.MediaDescription;
import com.google.gdata.data.media.mediarss.MediaKeywords;
import com.google.gdata.data.media.mediarss.MediaTitle;
import com.google.gdata.data.youtube.VideoEntry;
import com.google.gdata.data.youtube.YouTubeMediaGroup;
import com.google.gdata.data.youtube.YouTubeNamespace;
import com.google.gdata.data.youtube.YtPublicationState;
import com.google.gdata.util.ServiceException;

public class YouTubeShareTest {
   
private static final Logger logger = Logger.getLogger(YouTubeShareTest.class);
   
private static final String UPLOAD_URL =
           
"http://uploads.gdata.youtube.com/feeds/api/users/default/uploads";
   
public static final String ERROR = "error: ";
   
   
private YouTubeService service;
   
private URL uploadEndpoint;
   
private String clientId;
   
private String developerKey;
   
   
public YouTubeShareTest(String clientId, String developerKey) {
       
this.clientId = clientId;
       
this.developerKey = developerKey;
        service
= new YouTubeService(clientId, developerKey);
       
try {
            uploadEndpoint
= new URL(UPLOAD_URL);
       
} catch (MalformedURLException e) {
            logger
.error("Bad YouTube upload url", e);
       
}
   
}
   
   
public String upload(YouTubeUpload upload) {
       
StringBuilder result = new StringBuilder(ERROR);
       
VideoEntry vid = buildVideoEntry(upload);
       
VideoEntry created = null;        
       
try {
            service
.setHeader("Authorization", "Bearer <access token here>");
           
boolean success = false;
           
int retries = 3;
           
while (!success && retries-- > 0) {
                created
= service.insert(uploadEndpoint, vid);
                success
= true;
           
}
       
} catch (IOException e) {
            logger
.error("I/O problem uploading video", e);
            result
.append("I/O problem uploading video: ").append(e.getMessage());
       
} catch (ServiceException e) {
            logger
.error("YouTube service exception; responseBody="+e.getResponseBody(), e);
            result
.append("YouTube service exception: ").append(e.getMessage());
       
}
       
if (created != null) {
           
YtPublicationState pubState = created.getPublicationState();
           
if (pubState == null) {
               
//note: null is actually good; it means the video is live
                result
= new StringBuilder(created.getId());
           
} else if (pubState.getState() == YtPublicationState.State.REJECTED) {
                result
.append("video has been rejected. ");
                result
.append("reason: ").append(pubState.getDescription());
                result
.append(" for more info see: ").append(pubState.getHelpUrl());
           
} else if (pubState.getState() == YtPublicationState.State.FAILED) {
                result
.append("video upload failed. ");
                result
.append("reason: ").append(pubState.getDescription());
                result
.append(" for more info see: ").append(pubState.getHelpUrl());
           
} else {
                result
= new StringBuilder(created.getId());
           
}
       
}
       
return result.toString();
   
}
   
   
   
private VideoEntry buildVideoEntry(YouTubeUpload upload) {
       
VideoEntry newEntry = new VideoEntry();

       
YouTubeMediaGroup mg = newEntry.getOrCreateMediaGroup();
        mg
.setTitle(new MediaTitle());
        mg
.getTitle().setPlainTextContent(upload.getTitle());
        mg
.addCategory(new MediaCategory(YouTubeNamespace.CATEGORY_SCHEME, "Sports"));
        mg
.setKeywords(new MediaKeywords());
       
for (String keyword : upload.getKeywords()) {
            mg
.getKeywords().addKeyword(keyword);
       
}
       
//tag all our videos "Contour"
        mg
.getKeywords().addKeyword("Contour");
        mg
.setDescription(new MediaDescription());
       
StringBuilder contourDescription = new StringBuilder(upload.getDescription());
        contourDescription
.append("\n\nShot with a Contour. See the original at http://contour.com/stories/");
        contourDescription
.append(upload.getNid()).append(" .");
        mg
.getDescription().setPlainTextContent(contourDescription.toString());
        mg
.setPrivate(false);
       
       
MediaFileSource ms = new MediaFileSource(upload.getUploadFile(), "video/quicktime");
        newEntry
.setMediaSource(ms);

       
return newEntry;
   
}
   
   
   
public static void main(String[] args) {
       
YouTubeShareTest share = new YouTubeShareTest("<my client id here>", "<my client secret here>");
       
HttpClient c = new HttpClient(new MultiThreadedHttpConnectionManager());
       
YouTubeUpload upload = new YouTubeUpload();
        upload
.setTitle("Test of YT upload API");
        upload
.setDescription("just testing...");
        upload
.setUploadFile(new File(args[0]));
        upload
.addKeyword("foo");
        upload
.addKeyword("bar");
        upload
.setNid("123");
        share
.upload(upload);
   
}
   
}
...


--
You received this message because you are subscribed to the Google Groups "YouTube APIs Developer Forum" group.
To view this discussion on the web visit https://groups.google.com/d/msg/youtube-api-gdata/-/rjIB61NOr5EJ.
To post to this group, send email to youtube-api-gdata@googlegroups.com.
To unsubscribe from this group, send email to youtube-api-gdata+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/youtube-api-gdata?hl=en.

No comments:

Post a Comment