android - 读取下载的文本文件 - 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;
}
解决方案
只需将用户代理添加到您的 httpURL 连接。
HttpURLConnection httpURLconnection = (HttpURLConnection) url.openConnection();
httpURLconnection.setRequestProperty("User-Agent","MyAppName/1.0");
推荐阅读
- python - 无法使用 seaborn 绘制双轴
- terraform - 在 terragrunt 配置之间共享 aws_route53_record?
- laravel - 从 Vue 发布到 Laravel 时,Laravel 重定向不起作用
- python - 使用 scipy.optimize 中的 curve_fit 拟合数据后,如何确定某个 x 处的 y_predicted?
- angular - 根据另一个值验证一个角度反应形式的输入字段
- javascript - 使用 Angular 6 和 Billboard.js 图表库出现构建错误
- python - 通过反转图像的宽度和长度来顺时针旋转图像不起作用
- excel - 从数据透视表中的 PivotCell 获取 ParentNodeName
- python - 无法从 http://automatetheboringstuff.com/appendixa/ 安装第三方模块
- reactjs - AWS Amplify federatedSignIn 错误:无法读取未定义的属性“_config”