读取下载的文本文件-Android-错误-FileNotFoundException

时间:2018-07-29 16:54:24

标签: android

我正在尝试从此Google翻译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错误。

拜拜它是因为网址下载了.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;
        }

1 个答案:

答案 0 :(得分:1)

只需将用户代理添加到您的httpURLconnection。

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