zoukankan      html  css  js  c++  java
  • 针对幸运菜谱中乱码问题的进一步改进

    针对幸运菜谱中乱码问题的进一步改进

    主要改一下net方法,出现乱码原因:

    1.使用inputstream和outputstream都只是提供对字节或字节数组的读取方法,但是汉字占两个字节,如果使用字节流,读取不好就会出现乱码,故需要采用字符流reader

    2.创建reader的时候设置编码格式为UTF-8

    改进后的net方法如下:

    public static String net(String strUrl, Map params,String method) throws Exception {
            HttpURLConnection conn = null;
            BufferedReader reader = null;
            String rs = null;
            try {
                StringBuffer sb = new StringBuffer();
                if(method==null || method.equals("GET")){
                    strUrl = strUrl+"?"+urlencode(params);
                }
                URL url = new URL(strUrl);
                conn = (HttpURLConnection) url.openConnection();
                if(method==null || method.equals("GET")){
                    conn.setRequestMethod("GET");
                }else{
                    conn.setRequestMethod("POST");
                    conn.setDoOutput(true);
                }
                conn.setRequestProperty("User-agent", userAgent);
                conn.setUseCaches(false);
                conn.setConnectTimeout(DEF_CONN_TIMEOUT);
                conn.setReadTimeout(DEF_READ_TIMEOUT);
                conn.setInstanceFollowRedirects(false);
                conn.connect();
                if (params!= null && method.equals("POST")) {
                    try {
                        DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                        out.writeBytes(urlencode(params));
                    } catch (Exception e) {
                        // TODO: handle exception
                    }
                }
                InputStream is = conn.getInputStream();
                reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
                String strRead = null;
                while ((strRead = reader.readLine()) != null) {
                    sb.append(strRead);
                }
                rs = sb.toString();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (reader != null) {
                    reader.close();
                }
                if (conn != null) {
                    conn.disconnect();
                }
            }
            return rs;
        }
    务实,说实话!
  • 相关阅读:
    Java -- Matrix的一点认识
    LeetCode -- Sort List
    在Eclipse中调用weka包实现分类
    LeetCode -- Maximum Depth of Binary Tree
    LeetCode -- Lowest Common Ancestor of a Binary Search Tree
    LeetCode -- Ugly Number II
    LeetCode -- Ugly Number
    LeetCode -- Move Zeroes
    LeetCode -- Best Time to Buy and Sell Stock III
    LeetCode -- Best Time to Buy and Sell Stock II
  • 原文地址:https://www.cnblogs.com/xtuxiongda/p/8541543.html
Copyright © 2011-2022 走看看