简体   繁体   中英

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.

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.

You are trying to read a byte stream (InputStream) through a character stream reader (InputStream Reader). You should be cautious while doing this. You need to specify the charset for the reader to interpret the incoming bytes correctly. So need to know the charset and encoding of the data being received and build the InputStreamReader with the same charset so the data is interpretted properly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM