2012-03-25 11 views
-1

サーブレットをテストするための単純な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(); 
    } 
} 
+2

実際の文字を調べて、間違った前提をどこに見ているのか分かりませんか? –

+0

if(s.toString()。equals(expected))。ですからまずstringbufferから文字列を作成してください。 toString()を追加すると助けになりました。そのような愚かな質問のためのソーリーは、仕事を得ることを試みる約2週間の間、正常に眠らない。 – user1255246

+0

@ user1255246 - この質問への回答を投稿する必要があります – RonK

答えて

2

コメントに記載されているOPは、問題はさまざまなタイプのオブジェクトを比較することにあります。 次のようにコードでは、オブジェクトが定義されています。この問題を解決します

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

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 

は、との条件を交換します。

+0

ありがとう!これは本当に助けになったものです – user1255246