Blogger API 示例代码
Blogger API Sample Code
所以这是我在 Whosebug 上的第一个问题,如果有什么我忽略的地方请告诉我!
我正在尝试从 public Blogger 博客获取 Blog post 数据,用于我正在进行的一些语言分析研究。尽管 java API 看起来很简单,但我发现 Google 在 https://developers.google.com/blogger/docs/3.0/reference/posts/list#examples 的代码示例不起作用,因为缺少许多依赖项,范围从 LocalServerReceiver() 到 OAuthorization 所需的一整套依赖项。 API 资源管理器工作正常,但显然,我需要一些东西用于我自己的代码。
我也尝试使用其他 Whosebug 问题的代码片段,我发现这些问题与我的相似,但仍然面临依赖性问题。
这是我看过的一些问题的列表,由于某种代码弃用,这些问题没有解决我的问题:
Google oauth2 api client is not working properly
Why does Java not allow me to use OAuth2Native methods here?
我已经使用 OAuthPlayground 获取授权码,并且一直在尝试复制 Proper Form of API request to Blogger using Java/App Engine -error 401 中 iamkhova 解决方案的一些功能。请注意,我实际上并没有尝试向我正在访问的任何博客写任何东西。我只是希望能够获取 post 数据进行分析。
目前,我刚刚更改了 iamkhova 的解决方案,删除了记录器,并添加了一个 getPosts() 函数,该函数复制了我从 Google 的示例代码中需要的内容。
public class BlogHandler
{
static final String API_KEY = {My API Key};
public Blogger blogger = null;
public Blog blog;
public java.util.List<Post> posts;
public BlogHandler() {}
public void executeGetBlogByUrl (String url) throws IOException {
GetByUrl request = blogger.blogs().getByUrl( url );
this.blog = request.setKey(API_KEY).execute();
}
public void getPosts() throws IOException
{
List postsListAction = blogger.posts().list(this.blog.getId());
// Restrict the result content to just the data we need.
postsListAction.setFields("items(author/displayName,content,published,title,url),nextPageToken");
// This step sends the request to the server.
PostList posts = postsListAction.execute();
// Now we can navigate the response.
int postCount = 0;
int pageCount = 0;
while (posts.getItems() != null && !posts.getItems().isEmpty()) {
for (Post post : posts.getItems()) {
System.out.println("Post #"+ ++postCount);
System.out.println("\tTitle: "+post.getTitle());
System.out.println("\tAuthor: "+post.getAuthor().getDisplayName());
System.out.println("\tPublished: "+post.getPublished());
System.out.println("\tURL: "+post.getUrl());
System.out.println("\tContent: "+post.getContent());
}
// Pagination logic
String pageToken = posts.getNextPageToken();
if (pageToken == null || ++pageCount >= 5) {
break;
}
System.out.println("-- Next page of posts");
postsListAction.setPageToken(pageToken);
posts = postsListAction.execute();
}
}
public void setupService () throws IOException {
AppIdentityCredential credential = null;
credential = new AppIdentityCredential(Arrays.asList(BloggerScopes.BLOGGER)); // Add your scopes here
this.blogger = new Blogger.Builder(new UrlFetchTransport(), new JacksonFactory(), credential).setApplicationName("chsBlogResearch").build();
}
}
目前,我遇到以下错误:
Exception in thread "main" com.google.apphosting.api.ApiProxy$CallNotFoundException: The API package 'memcache' or call 'Get()' was not found.
at com.google.apphosting.api.ApiProxy.get(ApiProxy.java:173)
at com.google.apphosting.api.ApiProxy.get(ApiProxy.java:171)
at com.google.appengine.api.utils.FutureWrapper.get(FutureWrapper.java:89)
at com.google.appengine.api.memcache.MemcacheServiceImpl.quietGet(MemcacheServiceImpl.java:26)
at com.google.appengine.api.memcache.MemcacheServiceImpl.get(MemcacheServiceImpl.java:49)
at com.google.appengine.api.appidentity.AppIdentityServiceImpl.getAccessToken(AppIdentityServiceImpl.java:286)
at com.google.api.client.googleapis.extensions.appengine.auth.oauth2.AppIdentityCredential.intercept(AppIdentityCredential.java:98)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:859)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
at BloggerData.BlogHandler.executeGetBlogByUrl(BlogHandler.java:29)
单击 MemcacheServiceImpl 和 AppIdentityServiceImpl 中错误的代码行告诉我此时没有代码行。我在 Eclipse 中使用 Maven 作为依赖项。
在此代码中我唯一不确定的是作用域的概念,但我认为这不应该导致我的错误。
如果有任何想法,我将不胜感激,因为获取此 post 数据比我想象的要费时得多!
更新: 对上述错误提供了更多见解。显然这个 ApiProxy jar 不能通过控制台应用程序调用。
这不是一个非常有用的答案,但它最终在我的情况下起作用了。
Google Java API 客户端已经过时了,所以我最终切换到了 Google API Python客户端,因为它更新得更好,而且 OAuth 实际上在 Python 客户端中工作。它位于:https://github.com/google/google-api-python-client。示例文件非常有用,而且非常直观。
请注意 Google 的 Java API 样本都已损坏,至少在 Blogger 方面是这样。
从多个链接中,我获得了以下独立的 java class WORKING for blogger api v3(使用 api 密钥和 oauth2 凭据)。尽管我必须在控制台上手动粘贴来自请求 uri 的令牌。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.blogger.BloggerScopes;
public class PostInsert {
private static final String REDIRECT_URI = "YOUR REDIRECT URI";
private static final String CLIENT_SECRET = "YOUR CLIENT SECRET";
private static final String CLIENT_ID = "YOUR CLIENT_ID";
public static void main(String[] args) {
try {
HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
JacksonFactory JSON_FACTORY = new JacksonFactory();
Credential credential = getCredentials(HTTP_TRANSPORT, JSON_FACTORY, Arrays.asList(BloggerScopes.BLOGGER));
final JSONObject obj = new JSONObject();
obj.put("id", "<enter your blogid>");
final JSONObject requestBody = new JSONObject();
requestBody.put("title", "adding on 15feb 1.56pm");
requestBody.put("content", "add this");
final HttpPost request = new HttpPost("https://www.googleapis.com/blogger/v3/blogs/<enter your blogid>/posts?key=<enter your api key>");
request.addHeader("Authorization", "Bearer " + credential.getAccessToken());
request.addHeader("Content-Type", "application/json");
HttpClient mHttpClient = new DefaultHttpClient();
request.setEntity(new StringEntity(requestBody.toString()));
final HttpResponse response = mHttpClient.execute(request);
System.out.println( response.getStatusLine().getStatusCode() + " " +
response.getStatusLine().getReasonPhrase()
);
} catch (JSONException | IOException | GeneralSecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static GoogleCredential getCredentials(HttpTransport httpTransport, JacksonFactory jacksonFactory,
List<String> scopes) throws IOException, GeneralSecurityException {
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jacksonFactory,
CLIENT_ID, CLIENT_SECRET, scopes).setAccessType("online").setApprovalPrompt("auto").build();
String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
System.out.println("Please open the following URL in your " + "browser then type the authorization code:");
System.out.println(" " + url);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String code = br.readLine();
GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
System.out.println("Response : " + response.toPrettyString());
GoogleCredential credential =
new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jacksonFactory)
.setClientSecrets(CLIENT_ID, CLIENT_SECRET)
.build();
credential.setAccessToken(response.getAccessToken());
return credential;
}
}
所以这是我在 Whosebug 上的第一个问题,如果有什么我忽略的地方请告诉我!
我正在尝试从 public Blogger 博客获取 Blog post 数据,用于我正在进行的一些语言分析研究。尽管 java API 看起来很简单,但我发现 Google 在 https://developers.google.com/blogger/docs/3.0/reference/posts/list#examples 的代码示例不起作用,因为缺少许多依赖项,范围从 LocalServerReceiver() 到 OAuthorization 所需的一整套依赖项。 API 资源管理器工作正常,但显然,我需要一些东西用于我自己的代码。
我也尝试使用其他 Whosebug 问题的代码片段,我发现这些问题与我的相似,但仍然面临依赖性问题。
这是我看过的一些问题的列表,由于某种代码弃用,这些问题没有解决我的问题:
Google oauth2 api client is not working properly
Why does Java not allow me to use OAuth2Native methods here?
我已经使用 OAuthPlayground 获取授权码,并且一直在尝试复制 Proper Form of API request to Blogger using Java/App Engine -error 401 中 iamkhova 解决方案的一些功能。请注意,我实际上并没有尝试向我正在访问的任何博客写任何东西。我只是希望能够获取 post 数据进行分析。
目前,我刚刚更改了 iamkhova 的解决方案,删除了记录器,并添加了一个 getPosts() 函数,该函数复制了我从 Google 的示例代码中需要的内容。
public class BlogHandler
{
static final String API_KEY = {My API Key};
public Blogger blogger = null;
public Blog blog;
public java.util.List<Post> posts;
public BlogHandler() {}
public void executeGetBlogByUrl (String url) throws IOException {
GetByUrl request = blogger.blogs().getByUrl( url );
this.blog = request.setKey(API_KEY).execute();
}
public void getPosts() throws IOException
{
List postsListAction = blogger.posts().list(this.blog.getId());
// Restrict the result content to just the data we need.
postsListAction.setFields("items(author/displayName,content,published,title,url),nextPageToken");
// This step sends the request to the server.
PostList posts = postsListAction.execute();
// Now we can navigate the response.
int postCount = 0;
int pageCount = 0;
while (posts.getItems() != null && !posts.getItems().isEmpty()) {
for (Post post : posts.getItems()) {
System.out.println("Post #"+ ++postCount);
System.out.println("\tTitle: "+post.getTitle());
System.out.println("\tAuthor: "+post.getAuthor().getDisplayName());
System.out.println("\tPublished: "+post.getPublished());
System.out.println("\tURL: "+post.getUrl());
System.out.println("\tContent: "+post.getContent());
}
// Pagination logic
String pageToken = posts.getNextPageToken();
if (pageToken == null || ++pageCount >= 5) {
break;
}
System.out.println("-- Next page of posts");
postsListAction.setPageToken(pageToken);
posts = postsListAction.execute();
}
}
public void setupService () throws IOException {
AppIdentityCredential credential = null;
credential = new AppIdentityCredential(Arrays.asList(BloggerScopes.BLOGGER)); // Add your scopes here
this.blogger = new Blogger.Builder(new UrlFetchTransport(), new JacksonFactory(), credential).setApplicationName("chsBlogResearch").build();
}
}
目前,我遇到以下错误:
Exception in thread "main" com.google.apphosting.api.ApiProxy$CallNotFoundException: The API package 'memcache' or call 'Get()' was not found.
at com.google.apphosting.api.ApiProxy.get(ApiProxy.java:173)
at com.google.apphosting.api.ApiProxy.get(ApiProxy.java:171)
at com.google.appengine.api.utils.FutureWrapper.get(FutureWrapper.java:89)
at com.google.appengine.api.memcache.MemcacheServiceImpl.quietGet(MemcacheServiceImpl.java:26)
at com.google.appengine.api.memcache.MemcacheServiceImpl.get(MemcacheServiceImpl.java:49)
at com.google.appengine.api.appidentity.AppIdentityServiceImpl.getAccessToken(AppIdentityServiceImpl.java:286)
at com.google.api.client.googleapis.extensions.appengine.auth.oauth2.AppIdentityCredential.intercept(AppIdentityCredential.java:98)
at com.google.api.client.http.HttpRequest.execute(HttpRequest.java:859)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:419)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.executeUnparsed(AbstractGoogleClientRequest.java:352)
at com.google.api.client.googleapis.services.AbstractGoogleClientRequest.execute(AbstractGoogleClientRequest.java:469)
at BloggerData.BlogHandler.executeGetBlogByUrl(BlogHandler.java:29)
单击 MemcacheServiceImpl 和 AppIdentityServiceImpl 中错误的代码行告诉我此时没有代码行。我在 Eclipse 中使用 Maven 作为依赖项。
在此代码中我唯一不确定的是作用域的概念,但我认为这不应该导致我的错误。
如果有任何想法,我将不胜感激,因为获取此 post 数据比我想象的要费时得多!
更新: 对上述错误提供了更多见解。显然这个 ApiProxy jar 不能通过控制台应用程序调用。
这不是一个非常有用的答案,但它最终在我的情况下起作用了。
Google Java API 客户端已经过时了,所以我最终切换到了 Google API Python客户端,因为它更新得更好,而且 OAuth 实际上在 Python 客户端中工作。它位于:https://github.com/google/google-api-python-client。示例文件非常有用,而且非常直观。
请注意 Google 的 Java API 样本都已损坏,至少在 Blogger 方面是这样。
从多个链接中,我获得了以下独立的 java class WORKING for blogger api v3(使用 api 密钥和 oauth2 凭据)。尽管我必须在控制台上手动粘贴来自请求 uri 的令牌。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.GeneralSecurityException;
import java.util.Arrays;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleAuthorizationCodeFlow;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.auth.oauth2.GoogleTokenResponse;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.jackson2.JacksonFactory;
import com.google.api.services.blogger.BloggerScopes;
public class PostInsert {
private static final String REDIRECT_URI = "YOUR REDIRECT URI";
private static final String CLIENT_SECRET = "YOUR CLIENT SECRET";
private static final String CLIENT_ID = "YOUR CLIENT_ID";
public static void main(String[] args) {
try {
HttpTransport HTTP_TRANSPORT = new NetHttpTransport();
JacksonFactory JSON_FACTORY = new JacksonFactory();
Credential credential = getCredentials(HTTP_TRANSPORT, JSON_FACTORY, Arrays.asList(BloggerScopes.BLOGGER));
final JSONObject obj = new JSONObject();
obj.put("id", "<enter your blogid>");
final JSONObject requestBody = new JSONObject();
requestBody.put("title", "adding on 15feb 1.56pm");
requestBody.put("content", "add this");
final HttpPost request = new HttpPost("https://www.googleapis.com/blogger/v3/blogs/<enter your blogid>/posts?key=<enter your api key>");
request.addHeader("Authorization", "Bearer " + credential.getAccessToken());
request.addHeader("Content-Type", "application/json");
HttpClient mHttpClient = new DefaultHttpClient();
request.setEntity(new StringEntity(requestBody.toString()));
final HttpResponse response = mHttpClient.execute(request);
System.out.println( response.getStatusLine().getStatusCode() + " " +
response.getStatusLine().getReasonPhrase()
);
} catch (JSONException | IOException | GeneralSecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static GoogleCredential getCredentials(HttpTransport httpTransport, JacksonFactory jacksonFactory,
List<String> scopes) throws IOException, GeneralSecurityException {
GoogleAuthorizationCodeFlow flow = new GoogleAuthorizationCodeFlow.Builder(httpTransport, jacksonFactory,
CLIENT_ID, CLIENT_SECRET, scopes).setAccessType("online").setApprovalPrompt("auto").build();
String url = flow.newAuthorizationUrl().setRedirectUri(REDIRECT_URI).build();
System.out.println("Please open the following URL in your " + "browser then type the authorization code:");
System.out.println(" " + url);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String code = br.readLine();
GoogleTokenResponse response = flow.newTokenRequest(code).setRedirectUri(REDIRECT_URI).execute();
System.out.println("Response : " + response.toPrettyString());
GoogleCredential credential =
new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jacksonFactory)
.setClientSecrets(CLIENT_ID, CLIENT_SECRET)
.build();
credential.setAccessToken(response.getAccessToken());
return credential;
}
}