使用Blogger API发布文章失败问题排查求助
Hey there! Let's break down your Blogger API post issue step by step—your core idea is on the right track, but there are several key mistakes and missing steps keeping you from publishing successfully.
1. Is this the correct way to publish posts with the Blogger API?
The high-level approach (sending a POST request to the Blogger API's posts endpoint) is correct, but your implementation has critical flaws in authorization, request formatting, and dependency usage that make it invalid. This isn't a properly working implementation of the API.
2. What necessary steps are you missing?
- Valid OAuth2 Authorization: The Blogger API requires a proper OAuth2 access token to authenticate your request (not a random string or client ID). You need to:
- Set up OAuth2 credentials in the Google Cloud Console for your app
- Request the
https://www.googleapis.com/auth/bloggerscope to get permission to create posts - Exchange an authorization code for a valid access token (follow Google's OAuth2 flow for mobile apps)
- Modern HTTP Client:
DefaultHttpClientis deprecated (removed in Android 6.0+), so you need to use a supported library like OkHttp or HttpURLConnection - Error Debugging: You're only checking the status code, but not reading the response body—this is essential to see why the request failed (e.g., "invalid token", "insufficient permissions")
- Proper Exception Handling: Network calls can throw IO exceptions, which your code doesn't catch, so failures might happen silently without triggering your toast
3. What errors are in your code?
Let's list the specific issues:
- Invalid Authorization Header: Your
Authorizationvalue is a client ID-like string, but the correct format isBearer {your_valid_access_token}. Without this, the API can't authenticate your request. - Incorrect Variable Naming: Your
mUserIdvariable is misnamed—it should be your Blog ID (found in your Blogger dashboard under Settings > Other > Blog ID), not a user ID. - Missing Exception Handling:
httpClient.execute(request)can throwIOException, which isn't caught—your thread might crash silently without showing the toast. - Deprecated HTTP Client:
DefaultHttpClientis no longer supported, leading to potential runtime errors on newer Android versions. - No Response Body Inspection: Even if you get a non-200 status code, you don't read the response's error message, so you can't diagnose exactly what went wrong (e.g., invalid token, missing scope).
Fixed Code Example (Using OkHttp)
Here's a revised version using OkHttp (a modern, supported HTTP client) with proper error handling and correct request formatting:
First, add OkHttp to your module-level build.gradle:
implementation 'com.squareup.okhttp3:okhttp:4.12.0'
Then the updated code:
private void addPost() { new Thread(() -> { // Replace these with your actual values String BLOG_ID = "YOUR_BLOG_ID_HERE"; String VALID_ACCESS_TOKEN = "YOUR_OAUTH2_ACCESS_TOKEN_HERE"; String API_KEY = "YOUR_API_KEY_HERE"; // Optional with OAuth2, but can be included OkHttpClient client = new OkHttpClient(); // Build the request body correctly JSONObject blogObj = new JSONObject(); JSONObject requestBody = new JSONObject(); try { blogObj.put("id", BLOG_ID); requestBody.put("kind", "blogger#post"); requestBody.put("blog", blogObj); requestBody.put("title", "TestingTheBlogOneTwo"); requestBody.put("content", "ContentExample"); } catch (JSONException e) { e.printStackTrace(); runOnUiThread(() -> Toast.makeText(getApplicationContext(), "JSON formatting error", Toast.LENGTH_SHORT).show()); return; } Request request = new Request.Builder() .url("https://www.googleapis.com/blogger/v3/blogs/" + BLOG_ID + "/posts?key=" + API_KEY) .addHeader("Authorization", "Bearer " + VALID_ACCESS_TOKEN) .addHeader("Content-Type", "application/json") .post(RequestBody.create(requestBody.toString(), MediaType.get("application/json"))) .build(); try (Response response = client.newCall(request).execute()) { if (!response.isSuccessful()) { // Read error body for debugging String errorBody = response.body() != null ? response.body().string() : "No error message"; String errorMsg = "Failed: " + response.code() + " - " + errorBody; runOnUiThread(() -> Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_LONG).show()); } else { runOnUiThread(() -> Toast.makeText(getApplicationContext(), "Post published successfully!", Toast.LENGTH_SHORT).show()); } } catch (IOException e) { e.printStackTrace(); runOnUiThread(() -> Toast.makeText(getApplicationContext(), "Network error: " + e.getMessage(), Toast.LENGTH_SHORT).show()); } }).start(); }
Key Notes for Success
- Get a Valid Access Token: Follow Google's OAuth2 for Android guide to implement the flow and retrieve a token with the
bloggerscope. - Verify Blog ID: Double-check that your Blog ID is correct (it's a long numeric string from your Blogger settings).
- Check API Permissions: Ensure your Google Cloud project has the Blogger API enabled, and your OAuth2 credentials are configured correctly for your app.
内容的提问来源于stack exchange,提问作者Spack king




