使用 HttpURLConnection URL 发送请求,解决字符编码问题

从HttpURLConnection实例将获取服务器返回的输入流写到BufferedReader时,转成utf-8格式。

(本作品为原创,如有不足之处,还望大牛多给意见。如需转载,请注明出处。谢谢!)

只需要在设置编码即可 reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));

代码如下:

public boolean methodName(String userId, String request) {
        try {
            SysConfig sysConfig = sysConfig.getConfigByKey("ID"); //根据ID获取配置数据
            String industryId = sysConfig.getFdStr3();
            Map<String, Object> requestMap = JsonUtil.json2map(request);
            String deptCode = (String) requestMap.get("deptCode");
            SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            JSONObject jsonObj = new JSONObject();
            jsonObj.put("shareRange", 0);// 分享范围: 0不允许分享,1只分享到美信 ,2不限
            jsonObj.put("createTime", formatter.format(new Date()));
            jsonObj.put("openType", 3);// 打开方式:openType=0 pc 移动端都不能打开,openType=1 只支持PC 、 openType=2 只支持移动 、openType=3 既支持PC也支持移动 //必传
            Calendar cale = Calendar.getInstance();
            int month = cale.get(Calendar.MONTH) + 1;
            String coverImgUrl = HrMailUtil.formatUrl("/upload/"+ month + "_month.jpg");
            String jumpUrl = "https://www.baidu.com/";
            jsonObj.put("coverImgUrl", coverImgUrl);// 封面图片
            jsonObj.put("jumpUrl", jumpUrl);// 封面图片
            HrOrgDept hrOrgDept = hrOrgDeptMapper.selectAllDeptLeader(deptCode);
            Map<String, Object> map = null;
            List<HrEmpPersonChangeLog> personLst = new ArrayList<HrEmpPersonChangeLog>();
            HrEmpPersonChangeLog psnLog = null;

            SysConfig config = sysConfigMapper.getConfigByKey("NAME");
            String host = config.getFdStr1();
            String appKey = config.getFdStr2();
            String ACCESS_TOKEN = config.getFdStr3();
            if (null != orgDept && orgDept.size() > 0) {
                deptCode = StringBuQi.buQi(hrOrgDept.getFdCode());
                map = PersonnelChangesGenerator.getInstance().getPersonnelChanges(deptCode);
                String title = this.getMessage("PERSON_CHANGE_INFO");
                title = title.replace("{totalEntry}",(String) map.get("totalEntry")).replace("{totalLeave}", (String) map.get("totalLeave"));
                jsonObj.put("title", title);
                psnLog = new HrEmpPersonChangeLog();
                psnLog.setFdId(IDGenerator.generateID());
                psnLog.setFdContent(jsonObj.toString());
                psnLog.setFdDeptCode(deptCode);
                psnLog.setFdTitle(title);
                String toUserId = hrOrgDept.getFdLeaderItcode().replace("/", ",");
                if (StringUtil.isNotNull(toUserId)) {
                    toUserId = toUserId.substring(1, toUserId.length());
                }
                psnLog.setFdTouser(toUserId);
                psnLog.setFdIndustryId(industryId);
                psnLog.setFdUrl(jumpUrl);
                String url = "{host}/www/bai/du?appKey={appKey}&touser={toUserId}&accessToken={token}&sourceType={type}";// 请求接口地址
                url = url.replace("{host}", host)
                        .replace("{appKey}", appKey)
                        .replace("{toUserId}", toUserId)
                        .replace("{token}", ACCESS_TOKEN)
                        .replace("{type}", "todo");
                String lastNet = url.toString().replace(" ", "");
                URL newUrl = new URL(lastNet);
                HttpURLConnection connection = (HttpURLConnection) newUrl.openConnection();
                connection.setDoOutput(true);
                connection.setDoInput(true);
                connection.setRequestMethod("GET");
                connection.setUseCaches(false);
                connection.setRequestProperty("Content-type","Application/json");
                connection.setInstanceFollowRedirects(true);
                connection.connect();
                DataOutputStream out = new DataOutputStream(connection.getOutputStream());
                out.write(jsonObj.toString().getBytes("utf-8"));
                out.flush();
                out.close();
                BufferedReader reader;
                StringBuffer sb = new StringBuffer();
                reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
                String lines;
                while ((lines = reader.readLine()) != null) {
                    sb.append(lines);
                }
                String result = sb.toString();
                Map<String, Object> json = JsonUtil.json2map(result);
                String pushid = String.valueOf(json.get("pushId"));
                String errcode = String.valueOf(json.get("errcode"));
                String errmsg = String.valueOf(json.get("errmsg"));
                psnLog.setPushid(pushid);
                psnLog.setErrcode(errcode);
                psnLog.setErrmsg(errmsg);
                personLst.add(psnLog);
                
            }
            if (!personLst.isEmpty()) {
                hrEmpPersonChangeLogMapper.insertBatch(personLst);
            }
            return true;
        } catch (ServiceException e) {
            throw new ServiceException(e.getErrorCode(), e.getMessage());
        } catch (Exception e) {
            ExceptionUtil.ExceptionLog(e);
            String message = e.getMessage();
            throw new ServiceException(ResultCode.FAILURE_302, message);
        }
    }

 

posted @ 2019-01-28 11:17  Mr.JimYi  阅读(9586)  评论(0编辑  收藏  举报