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;
        }
    务实,说实话!
  • 相关阅读:
    nginx优化:使用expires在浏览器端缓存静态文件
    nginx优化:worker_processes/worker_connections/worker_rlimit_nofile
    centos8平台使用ulimit做系统资源限制
    centos8平台nginx服务配置打开文件限制max open files limits
    nginx安全:配置allow/deny控制ip访问(ngx_http_access_module)
    python 菜鸟入门
    正则表达式预查询
    selenium 关键字驱动部分设计思路
    Idea安装Python插件并配置Python SDK
    ORACLE LOG的管理
  • 原文地址:https://www.cnblogs.com/xtuxiongda/p/8541543.html
Copyright © 2011-2022 走看看