如何正确读取utf8字符的url内容?

2023-12-29

    public class URLReader {
         public static byte[] read(String from, String to, String string){
          try {
           String text = "http://translate.google.com/translate_a/t?"+
                        "client=o&text="+URLEncoder.encode(string, "UTF-8")+
                        "&hl=en&sl="+from+"&tl="+to+"";

           URL url = new URL(text);
           BufferedReader in = new BufferedReader(
                        new InputStreamReader(url.openStream(), "UTF-8"));
           String json = in.readLine();
           byte[] bytes = json.getBytes("UTF-8");
           in.close();
           return bytes;
                    //return text.getBytes();
          }
          catch (Exception e) {
           return null;
          }
         }
        }

and:

public class AbcServlet extends HttpServlet {
 public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  resp.setContentType("text/plain;charset=UTF-8");
  resp.getWriter().println(new String(URLReader.read("pl", "en", "koń")));
 }
}

当我运行这个时,我得到:{"sentences"[{"trans":"end","orig":"koďż˝","translit":"","src_translit":""}],"src":"pl","server_time":30}所以 utf 无法正常工作,但如果我返回编码的网址:http://translate.google.com/translate_a/t?client=o&text=ko%C5%84&hl=en&sl=pl&tl=en并粘贴到网址栏,我得到正确的结果:{"sentences":[{"trans":"horse","orig":"koń","translit":"","src_translit":""}],"dict":[{"pos":"noun","terms":["horse"]}],"src":"pl","server_time":76}


byte[] bytes = json.getBytes("UTF-8");

为您提供 UTF-8 字节序列,因此 URLReader.read 也为您提供 UTF-8 字节序列

但您尝试在不指定编码器的情况下进行解码,即new String(URLReader.read("pl", "en", "koń"))所以Java将使用你的系统默认编码来解码(不是UTF-8)

Try :

new String(URLReader.read("pl", "en", "koń"), "UTF-8")

Update

这是我的机器上完整工作的代码:

public class URLReader {

    public static byte[] read(String from, String to, String string) {
        try {
            String text = "http://translate.google.com/translate_a/t?"
                    + "client=o&text=" + URLEncoder.encode(string, "UTF-8")
                    + "&hl=en&sl=" + from + "&tl=" + to + "";
            URL url = new URL(text);
            URLConnection conn = url.openConnection();
            // Look like faking the request coming from Web browser solve 403 error
            conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2.13) Gecko/20101203 Firefox/3.6.13 (.NET CLR 3.5.30729)");
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
            String json = in.readLine();
            byte[] bytes = json.getBytes("UTF-8");
            in.close();
            return bytes;
            //return text.getBytes();
        } catch (Exception e) {
            System.out.println(e);
            // becarful with returning null. subsequence call will return NullPointException.
            return null;
        }
    }
}

不要忘记将 ń 转义为 \u0144。 Java 编译器可能无法正确编译 Unicode 文本,因此最好用纯 ASCII 编写它。

public class AbcServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("text/plain;charset=UTF-8");
        byte[] read = URLReader.read("pl", "en", "ko\u0144");
        resp.getOutputStream().write(read) ;
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何正确读取utf8字符的url内容? 的相关文章

随机推荐

  • 提取每第 n 个字母(数字)

    我有一个包含行 名称 空格和零和一字符串的文件 我需要提取零和一字符串的每第 5 个字符 对结果求和 如果总和不为 0 保存名称到另一个文件中 1rt2 0001000000100000000000001010000100000000010
  • 框架“可扩展性良好”是什么意思?

    当阅读有关框架 net ruby on Rails django spring 等 时 我不断地看到某些框架的扩展性很好或不好 当有人说框架 可扩展性良好 时 这是什么意思 而说框架 可扩展性不好 又是什么意思 谢谢 当您根据并发用户绘制一
  • 简单的 Javascript 数学函数 - 加法/不起作用?

    这是我的功能 var ans X X Y Z 当我进入10 20 and 10 分别 加法位的结果为2010并不是30 我怎样才能解决这个问题 确保首先将字符串转换为数字 var X 10 var Y 20 var Z 10 X X una
  • 如何在 SQL*Plus 中打开存储过程并对其进行编辑

    我需要对一个过时的机器上的旧 Oracle 存储过程进行一些更改 该机器保留下来运行旧的遗留进程 我唯一可以连接到数据库的工具是 SQL加 如何将存储过程加载到内存中以在 SQL 中进行编辑Plus 我在网上找到的教程没有解释这是如何完成的
  • git push 说一切都是最新的,而实际上它绝对不是

    我有一个公共存储库 没有其他人对其进行分叉 拉取或其他任何操作 我对一个文件做了一些小的更改 成功提交它们 并尝试推送 它说 一切都是最新的 没有分支机构 我对 git 非常非常陌生 我不明白到底发生了什么 git remote show
  • 如何在SQL Server中为自动增量列指定特定值?

    我在 sql server 中有一个自动增量标识列 但我想为其中一行指定特定值 因此 编号方案如下 1 2 999 for the reserved entry 3 n 我怎样才能做到这一点 你需要使用IDENTITY INSERT SET
  • 适用于 iOS 的 Elasticsearch 客户端

    有人知道适用于 iOS 的 elasticsearch 客户端库吗 如果它也用 swift 编写 那就太好了 弹性搜索 客户端 部分显示了多个平台的多个库 但没有显示 iOS 的任何内容 我觉得一定有人这样做了 Cheers 我怀疑没有人这
  • Rust:使用结构向量的极坐标中的数据帧

    Problem 我想读入数据polars数据帧来自mysql数据库 我在用sqlx sqlx生成结构向量 例如 Vec
  • 安装oracle 11g后sql plus打不开

    我安装了 oracle 11g 我试图从命令提示符打开 sqlplus 但它在不到一秒的时间内打开和关闭 我也尝试从安装位置打开 sqlplus 它仍然显示出相同的行为 谁能帮我解决一下 由于其他一些错误 我已经卸载并安装了两次 oracl
  • Pyparsing 支持上下文相关语法吗?

    如果我的术语不正确 请原谅我 也许只要用 正确 的词语来描述我想要的东西就足以让我自己找到答案 我正在开发 ODL 对象描述语言 的解析器 据我所知 这是一种神秘的语言 现在仅由 NASA PDS 行星数据系统 这是 NASA 向公众提供数
  • git Android Studio 使用的 ssh-key

    我需要连接到一个组织 因此需要提供公共 ssh 密钥 但是 我不确定 Android Studio 使用哪个 ssh 密钥 我发现自己对 Android Studio 中的各种 ssh 选项感到困惑 它是否只是使用我当前 git 安装生成的
  • Laravel 在关系对象上的位置

    我正在使用 Laravel 5 0 开发一个 Web API 但我不确定我正在尝试构建的特定查询 我的课程如下 class Event extends Model protected table events public timestam
  • zsh:在函数中设置opt并使其粘住

    我正在尝试将分析添加到函数内部的 zshrc 中 via http stackoverflow com a 4351664 329700 profile startup PS4 usr local bin gdate s N N i gt
  • 在 ASP.NET 5 中使用 WebClient

    我正在使用 VS15 beta 并尝试使用 WebClient 虽然引用了 System Net 并且智能感知表明 WebClient 类可用 但在构建时出现以下错误 命名空间 System Net 中不存在类型或命名空间名称 WebCli
  • JavaScript - 从字符串变量获取数组对象

    var list OVER 30 true NUM OF JACKETS gt 3 COUNT TOTAL 500 var array getList array 0 OVER 30 true array 0 NUM OF JACKETS
  • 错误:无法为 pymssql 构建轮子,这是在 Mac M1 中安装基于 pyproject.toml 的项目所必需的

    我使用的是带有 M1 芯片的 MacBook 但似乎有很多东西没有针对它进行优化 pyodbc不适合我 所以我想使用pymssql 不过 当我尝试运行时遇到了这个问题pip install pymssql 错误如下 Using cached
  • Swift Swiftui - 将颜色保存到 UserDefaults 并从 @AppStorage 使用它

    在我的 MacOS 和 iOS 应用程序中 我使用从此处创建的颜色 https uiwjs github io ui color https uiwjs github io ui color 然后是 f e 工作正常 Color red 1
  • 无损 ffmpeg 转换/编码

    我在转换视频时寻找最好的质量 我只想使用无损音频和视频编码器以及一个好的容器 如何为 ffmpeg 启用无损 x264 vcodec 我目前使用ffmpeg i inputvideo s 1280x720 ar 48000 threads
  • 为什么 autograd 不产生中间变量的梯度?

    尝试了解渐变的表示方式以及 autograd 的工作原理 import torch from torch autograd import Variable x Variable torch Tensor 2 requires grad Tr
  • 如何正确读取utf8字符的url内容?

    public class URLReader public static byte read String from String to String string try String text http translate google