将字符串转换为byte []并返回到客户端和服务器之间的字符串

时间:2012-06-07 10:35:56

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

我正在向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和新的String函数时尝试使用UTF和ASCII编码,但我仍然得到像这样的字节结果[B @ 405c0ce0

1 个答案:

答案 0 :(得分:3)

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

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

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