You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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.

Common Causes & Debugging Steps

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 Translation class includes the correct fields with matching @SerializedName annotations (like translatedText and detectedSourceLanguage).
  • 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.xml includes the internet permission:
    <uses-permission android:name="android.permission.INTERNET" />
    
  • Google’s API only accepts HTTPS requests. Confirm your Retrofit baseUrl starts with https://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):
    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();
    
    Check Logcat for the exact request URL, parameters, and any error responses from Google.

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:
    public interface TranslateApi {
        @GET
        Call<APIResponse> translate(
            @Url String url,
            @Query("q") String textToTranslate,
            @Query("target") String targetLang,
            @Query("key") String apiKey
        );
    }
    
    Typos in parameter names (e.g., using lang instead of target) 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 03:55:10