朋友们,我试试谷歌翻译api,我按照所有给定的步骤,
下面是我的代码
public class AndroidTranslate extends Activity {
EditText MyInputText;
Button MyTranslateButton;
TextView MyOutputText;
private final String requestURL = "https://www.googleapis.com/language/translate/v2?key=";
private final String requestKey = "qqqqqqqqqqqqqqqqq";
private final String requestSrc = "&source=";
private final String requestDst = "&target=";
private final String requestTxt = "&q=";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyInputText = (EditText)findViewById(R.id.InputText);
MyTranslateButton = (Button)findViewById(R.id.TranslateButton);
MyOutputText = (TextView)findViewById(R.id.OutputText);
MyTranslateButton.setOnClickListener(MyTranslateButtonOnClickListener);
}
private Button.OnClickListener MyTranslateButtonOnClickListener
= new Button.OnClickListener(){
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String InputString;
String OutputString = null;
InputString = MyInputText.getText().toString();
/*try {
Translate.setHttpReferrer("http://android-er.blogspot.com/");
OutputString = Translate.execute(InputString,
Language.ENGLISH, Language.FRENCH);
} catch (Exception ex) {
ex.printStackTrace();
OutputString = "Error";
}*/
OutputString=requestTranslation("hello","en","fr");
MyOutputText.setText(OutputString);
//Log.i("OutputString", OutputString);
}
};
public String requestTranslation( String txt, String src, String dst ) {
String request = requestURL + requestKey + requestSrc + src + requestDst + dst + requestTxt;
try {
request += URLEncoder.encode( txt, "UTF-8" );
URL url = new URL( request );
URLConnection connection = url.openConnection();
connection.connect();
InputStreamReader inputStreamReader = new InputStreamReader( connection.getInputStream(), "UTF-8" );
BufferedReader in = new BufferedReader( inputStreamReader, 512 );
StringBuffer sb = new StringBuffer();
String line;
while ( ( line = in.readLine() ) != null ) {
sb.append( line );
}
in.close();
Toast.makeText(this, sb.toString(), Toast.LENGTH_SHORT).show();
return sb.toString();
}
catch ( Exception e ) {
e.printStackTrace();
Toast.makeText(this,e.getMessage(), Toast.LENGTH_SHORT).show();
}
return null;
}
}
当我运行时抛出异常“主机未解析:www.googleapis.com.443” 我想用不同语言翻译用户提供的文本, 我有些不对劲,请建议 谢谢