Search code examples
javainputstreamhttpurlconnectionhttp-put

Getting improper Output from HttpURLConnection InputStream


      URL url = new URL("http://soandso.com");
      String userpassword = username + ":" + password;
      conn = (HttpURLConnection)url.openConnection();
      conn.setDoOutput(true);         
      conn.setRequestMethod("POST");         
      BASE64Encoder enc = new sun.misc.BASE64Encoder();          
      String encodedAuthorization = enc.encode( userpassword.getBytes() );
      conn.setRequestProperty("Authorization", "Basic "+encodedAuthorization);
      OutputStreamWriter writer =new OutputStreamWriter(conn.getOutputStream());
      writer.write("ABC");
      writer.flush ();
      writer.close();
      BufferedReader rd =new BufferedReader(new InputStreamReader(conn.getInputStream()));
      while ((inputLine = rd.readLine()) != null)
      System.out.println(inputLine);

The Output I got follows.

ÃœNÄ°TESÄ° TOPLANTI SALONU

But The actual output is supposed to be -- G ÜNİTESİ TOPLANTI SALONU

Can anyone tell me how to fix this?

PS: The code is not from any servlet. Its not a java class.


Solution

  • This will use the system default character encoding:

    OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
    

    Likewise so will this:

    BufferedReader rd = new BufferedReader(
        new InputStreamReader(conn.getInputStream()));
    

    Using the system default encoding is almost always a bad idea, particularly for networking.

    Which encoding did you want to use for the POST? You should set the Content-Type header to specify which encoding you use, and obviously also specify it in the constructor call to OutputStreamWriter. Likewise you should use the Content-Type of the response to determine which encoding to specify in the InputStreamReader call.

    Generally speaking, it's things like this that make it worth using a higher-level HTTP library such as Apache HttpClient. That should be able to handle the encoding for you.