【问题标题】:Converting string to byte[] and back to string between client and server将字符串转换为 byte[] 并在客户端和服务器之间转换回字符串
【发布时间】:2012-06-07 10:35:56
【问题描述】:

我正在向 web 服务发送文本,但首先转换为字节,然后在服务器端接收到我想将字节更改回字符串。我已经能够转换为字节,但无法转换回字符串。我查看了很多关于 SO 的教程,但到目前为止似乎都没有。

这是客户端应用程序

try {   
        String text = "holiday";
        byte[] byte_text = text.getBytes();
        HttpClient client = new DefaultHttpClient();
        HttpGet request = new HttpGet();
        URI link = new URI("http://192.165.1.3:8080/HelloWorld/hello?text="+byte_text);
        request.setURI(link);
        HttpResponse response = client.execute(request);

    } catch (Exception e1) {
        e1.printStackTrace();
    }

这是我在客户端所做的

    byte[] why = req.getParameter("text").getBytes();
    String text = new String(why);
    System.out.println(text);

当我调用 getbyte 和 new String 函数时,我尝试使用 UTF 和 ASCII 编码,但我仍然得到像这样的字节结果 [B@405c0ce0

【问题讨论】:

  • 我在 JB;你到底想完成什么?
  • 为什么?将字节数组附加到 String 不会做您认为它会做的事情,而附加 String does 会做您认为前者应该做的事情。转换的意义何在?

标签: java string web-services servlets character-encoding


【解决方案1】:

在执行"http://192.168.0.3:8080/HelloWorld/hello?text=" + byte_text时,会在字节数组上调用toString()方法将其转换为String,并将该String附加到URL中。 byte[]toString() 方法返回 "[B@" 后跟对象的哈希码。

也就是说,您的代码确实没有意义。您有一个字符串并希望将其附加到 URL。将String转换为字节数组然后再将字节数组转换回String有什么意义?

有意义的是使用java.net.URLEncoder 来确保所有特殊字符都被正确编码,并且编码的结果可以安全地作为查询字符串参数附加。

【讨论】:

  • 我正在设计的应用程序必须处理许多具有特殊字符的不同语言。我注意到当我将文本作为字符串发送时,特殊字符被更改为其他字符,因此我决定尝试使用字节。有没有其他方法可以解决这个问题?
猜你喜欢
  • 2019-03-18
  • 1970-01-01
  • 2013-02-18
  • 2019-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-17
相关资源
最近更新 更多