Android中使用Retrofit调用谷歌翻译API每次触发onFailure问题
Hey there! Let's figure out why your Retrofit call to the Google Translate API keeps triggering the onFailure callback. I’ll break down the most common issues and how to debug them using your code context.
1. Google Translate API Authentication Issues
Google’s Translation API requires a valid, properly configured API key to work.
- Double-check that your API key is enabled for the Cloud Translation API in the Google Cloud Console. Also, confirm it hasn’t hit quota limits or been restricted by IP/usage rules.
- Ensure you’re passing the key correctly as a query parameter in your Retrofit request (e.g.,
?key=YOUR_API_KEY). Missing or invalid keys will almost always lead to failure.
2. Mismatch Between Your Model Classes and API Response
From the code snippets you shared (APIResponse, Data), you need to make sure your model perfectly matches the actual JSON structure returned by Google’s API. A typical successful response looks like this:
{ "data": { "translations": [ { "translatedText": "Hello", "detectedSourceLanguage": "es" } ] } }
- Verify your
Translationclass includes the correct fields with matching@SerializedNameannotations (liketranslatedTextanddetectedSourceLanguage). - If Gson encounters missing required fields or unexpected data types during parsing, it can trigger a failure. You can enable Gson’s lenient mode if needed, but fixing the model match is better.
3. Network & HTTPS Configuration
- Make sure your
AndroidManifest.xmlincludes the internet permission:<uses-permission android:name="android.permission.INTERNET" /> - Google’s API only accepts HTTPS requests. Confirm your Retrofit
baseUrlstarts withhttps://translation.googleapis.com/(not HTTP).
4. Retrofit Client Setup Issues
- Ensure you’ve added the Gson converter factory to your Retrofit instance—without it, Retrofit can’t parse the JSON response:
Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://translation.googleapis.com/language/translate/v2/") .addConverterFactory(GsonConverterFactory.create()) .build(); - Add a logging interceptor to see full request/response details (this is invaluable for debugging):
Check Logcat for the exact request URL, parameters, and any error responses from Google.HttpLoggingInterceptor logging = new HttpLoggingInterceptor(); logging.setLevel(HttpLoggingInterceptor.Level.BODY); OkHttpClient client = new OkHttpClient.Builder() .addInterceptor(logging) .build(); Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://translation.googleapis.com/language/translate/v2/") .client(client) .addConverterFactory(GsonConverterFactory.create()) .build();
5. Missing or Incorrect Request Parameters
Google’s API requires mandatory parameters like q (text to translate) and target (target language code).
- Verify your Retrofit interface method passes these parameters correctly:
Typos in parameter names (e.g., usingpublic interface TranslateApi { @GET Call<APIResponse> translate( @Url String url, @Query("q") String textToTranslate, @Query("target") String targetLang, @Query("key") String apiKey ); }langinstead oftarget) will cause the API to reject your request.
6. Extract Detailed Error Info
Always log the full error in your onFailure callback to pinpoint the root cause:
call.enqueue(new Callback<APIResponse>() { @Override public void onResponse(Call<APIResponse> call, Response<APIResponse> response) { // Handle success } @Override public void onFailure(Call<APIResponse> call, Throwable t) { t.printStackTrace(); // Print full exception stack trace Log.e("TranslateError", "Failure reason: " + t.getMessage()); } });
This will tell you if it’s a network issue (IOException), parsing error (JsonSyntaxException), or HTTP error (like 401 for invalid auth, 403 for quota limits).
内容的提问来源于stack exchange,提问作者matteofabris

