首页 > 解决方案 > 读取下载的文本文件 - Android - 错误 - FileNotFoundException

问题描述

我正在尝试从此 google translate API URL 获取数据:

String sourceLang = "auto";
String targetLang = "en";
String sourceText = "olas";
String urlstring = "https://translate.googleapis.com/translate_a/single?client=gtx&sl=" + sourceLang + "&tl=" + targetLang + "&dt=t&q=" + sourceText;

api url 在 python 上运行良好,但在 android 上我得到 filenotfoundexception 错误。

可能是因为 url 下载的是 .txt 文件而不是显示数据,如您所见:

https://translate.googleapis.com/translate_a/single?client=gtx&sl=auto&tl=en&dt=t&q=olas

这是我使用的代码:

        URL url = new URL(urlstring);
        HttpURLConnection httpURLconnection = (HttpURLConnection) url.openConnection();

        InputStream inputStream = httpURLconnection.getInputStream();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

        String line = "";
        while(line != null){
            line = bufferedReader.readLine();
            data = data + line;
        }

标签: android

解决方案


只需将用户代理添加到您的 httpURL 连接。

 HttpURLConnection httpURLconnection = (HttpURLConnection) url.openConnection();
 httpURLconnection.setRequestProperty("User-Agent","MyAppName/1.0");

推荐阅读