сравнение строк ответа сервлета - PullRequest
0 голосов
/ 25 марта 2012

У меня есть простой Java-класс для тестирования моего сервлета. Он отправляет JSON и получает XML, я сравниваю их и всегда получаю не равны, но они должны быть равны. В чем может быть проблема? Сервлет отправить 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 Ответ

2 голосов
/ 26 декабря 2012

Как указано в комментариях к ОП - проблема заключается в сравнении разных типов объектов. В коде объекты определены следующим образом:

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)) {... 

Решит проблему.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...