所以这是关于StackOverflow的第一个问题,所以请告诉我是否有一些我忽略的内容!
我正在尝试从公共Blogger博客获取Blog发布数据,以进行我正在进行的一些语言分析研究。尽管java API看起来很简单,但我发现Google https://developers.google.com/blogger/docs/3.0/reference/posts/list#examples的代码示例不起作用,因为缺少许多依赖项,从LocalServerReceiver()到OAuthorization所需的一系列依赖项。 API资源管理器工作正常,但显然,我需要一些代码来自我自己的代码。
我也尝试过利用其他StackOverflow问题中的代码片段,我看到这些问题与我的相似,但我仍面临依赖问题。
以下列出了我所看到的一些问题,由于某些代码弃用,这些问题尚未解决我的问题:
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解决方案的一些功能。请注意,我实际上并没有尝试向我正在访问的任何博客写任何内容。我只是希望能够获得后期数据进行分析。
目前我刚刚通过取出记录器改变了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$1.get(ApiProxy.java:173)
at com.google.apphosting.api.ApiProxy$1.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来实现依赖。
我在这段代码中唯一不确定的是范围的想法,但我认为这不应该导致我的错误。
我很感激任何有关这方面的想法,因为获取这些帖子数据比我想象的更费时!
更新:getting strange exception trying to implement asynchronous http in google app engine for java提供了有关上述错误的更多信息。显然,无法通过控制台应用程序调用此ApiProxy jar。
答案 0 :(得分:1)
这不是一个非常有用的答案,但它最终会在我的情况下起作用。
Google Java API客户端已经过时了,所以我最终转而使用Google API Python客户端,因为它的更新效果更好,OAuth实际上可以在Python客户端中运行。它位于:https://github.com/google/google-api-python-client。示例文件非常有用,而且非常直观。
请注意,Google的Java API示例都已损坏,至少在Blogger方面是这样。
答案 1 :(得分:0)
从多个链接中,我获得了以下独立的java类WORKING for blogger api v3(使用了api key和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;
}
}