比较字符串servlet响应

时间:2012-03-25 15:32:10

标签: java string servlets

有一个简单的java类来测试我的servlet。它发送json并接收xml,我比较它们并且总是不相等,但它们应该相等。可能是什么问题呢? Servlet发送UTF-8。和字符串看起来相同但不一样。

public static void main(String[] args) throws URISyntaxException,
        HttpException {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://localhost:8080/converter/cs");
    String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><sample><color type=\"string\">red</color></sample>";
    try {
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        nameValuePairs.add(new BasicNameValuePair("json",
                "{\"color\": \"red\"}"));

        post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        HttpResponse response = client.execute(post);
        BufferedReader rd = new BufferedReader(new InputStreamReader(
                response.getEntity().getContent()));
        String line = "";
        StringBuilder s = new StringBuilder();
        while ((line = rd.readLine()) != null) {
            System.out.println(line);
            s.append(line);
        }
        System.out.println(s.length());
        System.out.println(expected.length());
        System.out.println(s.toString());
        if (s.equals(expected)) {
            System.out.println("equal");
        } else
            System.out.println("not equal");
    } catch (IOException e) {
        e.printStackTrace();
    }
}

1 个答案:

答案 0 :(得分:2)

正如评论中提到的OP一样 - 问题在于比较不同类型的对象。 在代码中,对象定义如下:

String expected = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><sample><color type=\"string\">red</color></sample>";
...
    StringBuilder s = new StringBuilder();
    ...
       s.append(...);
    ...
    if (s.equals(expected)) {... // The problem is here, s and expected are not of the same class

用以下内容替换条件:

    if (s.toString().equals(expected)) {... 

将解决问题。