5

我在用

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    TextView tv = new TextView(this);

     GoogleAPI.setHttpReferrer("http://code.google.com/p/google-api-translate-java/");
     GoogleAPI.setKey("AIzaSyBi7y4EgC0B-Q9UZg-tOzsOI0sLQ8F1Oow");

        try {
            String translatedText = Translate.DEFAULT.execute("Bonjour le monde", Language.FRENCH, Language.ENGLISH);
        } catch (GoogleAPIException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

}

我收到以下错误,我不明白我做错了什么

02-26 10:53:53.409: W/System.err(2612): com.google.api.GoogleAPIException: java.lang.Exception: [google-api-translate-java] Error retrieving translation. 02-26 10:53:53.409: W/System.err(2612): at com.google.api.translate.TranslateV2.execute(TranslateV2.java:68) 02-26 10:53:53.409: W/System.err(2612): at com.example.testtranslate.Translator.onCreate(Translator.java:32) 02-26 10:53:53.409: W/System.err(2612): at android.app.Activity.performCreate(Activity.java:5158) 02-26 10:53:53.409: W/System.err(2612): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080) 02-26 10:53:53.409: W/System.err(2612): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2148) 02-26 10:53:53.409: W/System.err(2612): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2211) 02-26 10:53:53.410: W/System.err(2612): at android.app.ActivityThread.access$600(ActivityThread.java:149) 02-26 10:53:53.410: W/System.err(2612): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1300) 02-26 10:53:53.411: W/System.err(2612): at android.os.Handler.dispatchMessage(Handler.java:99) 02-26 10:53:53.411: W/System.err(2612): at android.os.Looper.loop(Looper.java:153) 02-26 10:53:53.411: W/System.err(2612): at android.app.ActivityThread.main(ActivityThread.java:5086) 02-26 10:53:53.412: W/System.err(2612): at java.lang.reflect.Method.invokeNative(Native Method) 02-26 10:53:53.412: W/System.err(2612): at java.lang.reflect.Method.invoke(Method.java:511) 02-26 10:53:53.412: W/System.err(2612): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821) 02-26 10:53:53.413: W/System.err(2612): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584) 02-26 10:53:53.413: W/System.err(2612): at dalvik.system.NativeStart.main(Native Method) 02-26 10:53:53.413: W/System.err(2612): Caused by: java.lang.Exception: [google-api-translate-java] Error retrieving translation. 02-26 10:53:53.414: W/System.err(2612): at com.google.api.GoogleAPI.retrieveJSON(GoogleAPI.java:99) 02-26 10:53:53.414: W/System.err(2612): at com.google.api.translate.TranslateV2.execute(TranslateV2.java:62) 02-26 10:53:53.416: W/System.err(2612): ... 15 more 02-26 10:53:53.416: W/System.err(2612): Caused by: java.lang.NullPointerException 02-26 10:53:53.418: W/System.err(2612): at libcore.net.http.HttpEngine.writeRequestHeaders(HttpEngine.java:647) 02-26 10:53:53.418: W/System.err(2612): at libcore.net.http.HttpEngine.readResponse(HttpEngine.java:801) 02-26 10:53:53.419: W/System.err(2612): at libcore.net.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:293) 02-26 10:53:53.419: W/System.err(2612): at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:185) 02-26 10:53:53.420: W/System.err(2612): at libcore.net.http.HttpsURLConnectionImpl.getInputStream(HttpsURLConnectionImpl.java:271) 02-26 10:53:53.420: W/System.err(2612): at com.google.api.GoogleAPI.retrieveJSON(GoogleAPI.java:93) 02-26 10:53:53.420: W/System.err(2612): ... 16 more

4

4 回答 4

2

需要将引荐来源网址设置为您从中发送请求的应用程序 URL。

https://developers.google.com/console/help/new/

这几乎总是一个访问配置问题。尝试查看请求的 URL 的响应。响应将类似于:

{ "error": { "errors": [ { "domain": "usageLimits", "reason": "accessNotConfigured", "message": "访问未配置。请使用 Google Developers Console 为您的项目激活 API。 " } ], "code": 403, "message": "Access Not Configured. 请使用 Google Developers Console 为您的项目激活 API。" } }

于 2014-02-07T12:05:36.483 回答
0

您可能忘记授予权限:

只需要将它添加到我的清单中:

<uses-permission android:name="android.permission.INTERNET"/>
于 2013-11-16T09:16:11.513 回答
0

您必须从 API 控制台中项目的服务选项卡启用翻译 API。

此页面包含所有定价详细信息:https ://developers.google.com/translate/v2/pricing

于 2014-05-25T18:56:21.030 回答
0

这种方法对我完全不起作用,所以我决定改用 Web API。这是我的代码:

package your.package.name;

import android.util.Log;

import com.google.api.translate.Language;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;

/**
 * Created by nick hargreaves on 4/23/15.
 */


public class GTranslate {

    public static String GOOGLE_API_KEY = "your api key";

    public static String translatedText(String text, Language lTranslated, Language lOriginal){

        if(lTranslated.equals(lOriginal))
            return text;

        text = URLEncoder.encode(text);

        String translatedText = "";

        String sOriginal = findLanguageCode(lOriginal.name());

        String sTranslated = findLanguageCode(lTranslated.name());

        String requestURL = "https://www.googleapis.com/language/translate/v2?key="+ GOOGLE_API_KEY+"&q="+text+"&source="+sOriginal+"&target=" + sTranslated;

        String readJSON = getJSON(requestURL);

        try{
            JSONObject jsonObject = new JSONObject(readJSON).getJSONObject("data");

            jsonObject = jsonObject.getJSONArray("translations").getJSONObject(0);

            translatedText = jsonObject.getString("translatedText");

        } catch(Exception e){e.printStackTrace();}
        finally{System.out.println("Success");}

        return translatedText;
    }

    public static String getJSON(String address){
        StringBuilder builder = new StringBuilder();
        HttpClient client = new DefaultHttpClient();
        HttpGet httpGet = new HttpGet(address);
        try{
            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if(statusCode == 200){
                HttpEntity entity = response.getEntity();
                InputStream content = entity.getContent();
                BufferedReader reader = new BufferedReader(new InputStreamReader(content));
                String line;
                while((line = reader.readLine()) != null){
                    builder.append(line);
                }
            } else {
                Log.e("JSON error", "Failed to get JSON object");
            }
        }catch(ClientProtocolException e){
            e.printStackTrace();
        } catch (IOException e){
            e.printStackTrace();
        }
        return builder.toString();
    }

    public static String findLanguageCode(String language){
        String languageShort = "en";

        if(language=="AFRIKAANS"){
            languageShort="af";
        }
        if(language=="ALBANIAN"){
            languageShort="sq";
        }
        if(language=="ARABIC"){
            languageShort="ar";
        }
        if(language=="AZERBAIJANI"){
            languageShort="az";
        }
        if(language=="BASQUE"){
            languageShort="eu";
        }
        if(language=="BENGALI"){
            languageShort="bn";
        }
        if(language=="BELARUSIAN"){
            languageShort="be";
        }
        if(language=="BULGARIAN"){
            languageShort="bg";
        }
        if(language=="CATALAN"){
            languageShort="ca";
        }
        if(language=="CHINESE SIMPLIFIED"){
            languageShort="zh-CN";
        }
        if(language=="CHINESE TRADITIONAL"){
            languageShort="zh-TW";
        }
        if(language=="CROATIAN"){
            languageShort="hr";
        }
        if(language=="CZECH"){
            languageShort="cs";
        }
        if(language=="DANISH"){
            languageShort="da";
        }
        if(language=="DUTCH"){
            languageShort="nl";
        }
        if(language=="ENGLISH"){
            languageShort="en";
        }
        if(language=="ESPERANTO"){
            languageShort="eo";
        }
        if(language=="ESTONIAN"){
            languageShort="et";
        }
        if(language=="FILIPINO"){
            languageShort="tl";
        }
        if(language=="FINNISH"){
            languageShort="fi";
        }
        if(language=="FRENCH"){
            languageShort="fr";
        }
        if(language=="GALICIAN"){
            languageShort="gl";
        }
        if(language=="GEORGIAN"){
            languageShort="ka";
        }
        if(language=="GERMAN"){
            languageShort="de";
        }
        if(language=="GREEK"){
            languageShort="el";
        }
        if(language=="GUJARATI"){
            languageShort="gu";
        }
        if(language=="HAITIAN CREOLE"){
            languageShort="ht";
        }
        if(language=="HEBREW"){
            languageShort="iw";
        }
        if(language=="HINDI"){
            languageShort="hi";
        }
        if(language=="HUNGARIAN"){
            languageShort="hu";
        }
        if(language=="ICELANDIC"){
            languageShort="is";
        }
        if(language=="INDONESIAN"){
            languageShort="id";
        }
        if(language=="IRISH"){
            languageShort="ga";
        }
        if(language=="ITALIAN"){
            languageShort="it";
        }
        if(language=="JAPANESE"){
            languageShort="ja";
        }
        if(language=="KANNADA"){
            languageShort="kn";
        }
        if(language=="KOREAN"){
            languageShort="ko";
        }
        if(language=="LATIN"){
            languageShort="la";
        }
        if(language=="LATVIAN"){
            languageShort="lv";
        }
        if(language=="LITHUANIAN"){
            languageShort="lt";
        }
        if(language=="MACEDONIAN"){
            languageShort="mk";
        }
        if(language=="MALAY"){
            languageShort="ms";
        }
        if(language=="MALTESE"){
            languageShort="mt";
        }
        if(language=="NORWEGIAN"){
            languageShort="no";
        }
        if(language=="PERSIAN"){
            languageShort="fa";
        }
        if(language=="POLISH"){
            languageShort="pl";
        }
        if(language=="PORTUGUESE"){
            languageShort="pt";
        }
        if(language=="ROMANIAN"){
            languageShort="ro";
        }
        if(language=="RUSSIAN"){
            languageShort="ru";
        }
        if(language=="SERBIAN"){
            languageShort="sr";
        }
        if(language=="SLOVAK"){
            languageShort="sk";
        }
        if(language=="SLOVENIAN"){
            languageShort="sl";
        }
        if(language=="SPANISH"){
            languageShort="es";
        }
        if(language=="SWAHILI"){
            languageShort="sw";
        }
        if(language=="SWEDISH"){
            languageShort="sv";
        }
        if(language=="TAMIL"){
            languageShort="ta";
        }
        if(language=="TELUGU"){
            languageShort="te";
        }
        if(language=="THAI"){
            languageShort="th";
        }
        if(language=="TURKISH"){
            languageShort="tr";
        }
        if(language=="UKRAINIAN"){
            languageShort="uk";
        }
        if(language=="URDU"){
            languageShort="ur";
        }
        if(language=="VIETNAMESE"){
            languageShort="vi";
        }
        if(language=="WELSH"){
            languageShort="cy";
        }
        if(language=="YIDDISH"){
            languageShort="yi";
        }

        return languageShort;
    }

}

然后这样称呼它:

import com.google.api.translate.Language;
import com.your.package.name.GTranslate;

...

String translatedText = GTranslate.translatedText("Some text I want to translate Russian", Language.RUSSIAN, Language.ENGLISH);
于 2015-04-23T11:35:16.693 回答