Java - http carried out by Chinese garbled URLConnection request

 

Writer and reader to specify the character set

out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8"));
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));

Specific code:

    public  static String sendPost (URL String, String param) { 
        the PrintWriter OUT = null ; 
        the BufferedReader in = null ; 
        String Result = "" ;
         the try { 
            the URL realUrl = new new the URL (URL);
             // open a connection and the URL 
            the URLConnection Conn = realUrl.openConnection ();
             // set the common request attribute 
            conn.setRequestProperty ( "Accept", "* / *" ); 
            conn.setRequestProperty ( "Connection", "the Keep-Alive" );
            conn.setRequestProperty ( "User-Agent", "the Mozilla / 4.0 (compatible; MSIE 6.0; the Windows NT 5.1; SVl)" ); 
            
            
            // send a POST request must set the following two lines 
            conn.setDoOutput ( to true ); 
            conn.setDoInput ( to true );
             // Get URLConnection object corresponding to the output stream 
            OUT = new new the PrintWriter ( new new the OutputStreamWriter (conn.getOutputStream (), "UTF-. 8" ));
             // send a request parameter 
            Out.print (param);
             // the flush output buffer flow 
            out.flush ();
             // define BufferedReader input stream to read the URL of the response 
            in =new new the BufferedReader ( new new the InputStreamReader (conn.getInputStream (), "UTF-. 8" )); 
            String Line; 
            the while (! (= in.readLine Line ()) = null ) { 
                Result + = Line; 
            } 
        } the catch (Exception E ) { 
            System.out.println ( "POST request transmission abnormality!" + E); 
            e.printStackTrace (); 
        } 
        // use the finally block to close the output stream, the input stream 
        finally {
             the try {
                 IF (OUT =! null ) { 
                    OUT .close ();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

 

Guess you like

Origin www.cnblogs.com/yarightok/p/11544439.html