• HttpURLConnection发送中文乱码问题解决


    /**
         * 发送http POST请求
         *
         * @param
         * @return 远程响应结果
         */
        public static String sendPost(String u, String json) throws Exception {
            StringBuffer sbf = new StringBuffer();
            try {
                URL url = new URL(u);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setDoInput(true);
                connection.setDoOutput(true);
                connection.setRequestMethod("POST");
                connection.setUseCaches(false);
                connection.setInstanceFollowRedirects(true);
                connection.addRequestProperty("Content-Type", "application/json");
                connection.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
                connection.connect();
                DataOutputStream out = new DataOutputStream(connection.getOutputStream());
                if (!"".equals(json)) {
                    //out.writeBytes(json);
                    out.write(json.getBytes());
                }
                out.flush();
                out.close();
    
                BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
                String lines;
                while ((lines = reader.readLine()) != null) {
                    lines = new String(lines.getBytes(), "utf-8");
                    sbf.append(lines);
                }
                System.out.println(sbf);
                reader.close();
                // 断开连接
                connection.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
                throw e;
            }
            return sbf.toString();
        }

    重点在于:替换out.writeBytes(json);为 out.write(json.getBytes());

    原因为:out.writeBytes(json);该语句在转中文时候,已经变成乱码

    public final void writeBytes(String s) throws IOException {
    int len = s.length();
    for (int i = 0 ; i < len ; i++) {
    out.write((byte)s.charAt(i));
    }
    incCount(len);
    }

    因为java里的char类型是16位的,一个char可以存储一个中文字符,在将其转换为 byte后高8位会丢失,这样就无法将中文字符完整的输出到输出流中。所以在可能有中文字符输出的地方最好先将其转换为字节数组,然后再通过write写入流,

     

  • 相关阅读:
    网页工具KOBAS进行KEGG富集分析
    Novel LncRNA的实时定量PCR引物设计教程
    Annotated LncRNA的实时定量PCR引物设计教程
    GO分析-GOseq的使用教程
    转录因子预测-oPOSSUM 3.0的使用教程
    miRNA结合位点预测软件RNAhybrid的使用教程
    关于win10用户名设置为中文导致Rstudio画图报错的解决方法
    edgeR之配对检验分析差异基因的使用教程
    51nod 1051最大子矩阵和
    51nod最大字段和(1049 1254)
  • 原文地址:https://www.cnblogs.com/liangblog/p/15500221.html
Copyright © 2020-2023  润新知