JDK发送Http请求


        HttpURLConnection conn = null;
        InputStream is = null;
        BufferedReader reader = null;
        String msg;
        try {
            String sClientVersion = String.valueOf(clientVersion);
            httpUrl = MessageFormat.format(httpUrl, sClientVersion,Prop.provinceId);
            URL url = new URL(httpUrl);
            conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("POST");
            conn.setRequestProperty("Connection", "close");
            conn.connect();
            int resCode = conn.getResponseCode();
            if (resCode == HttpURLConnection.HTTP_OK) {
                is = conn.getInputStream();
                reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                StringBuffer sb = new StringBuffer();
                String strRead = null;
                while ((strRead = reader.readLine()) != null) {
                    sb.append(strRead);
                }
                msg = sb.toString();
                JSONObject jobj = JSONObject.fromObject(msg);

                String returnCode = (String) jobj.get("returnCode");
                if ("0".equals(returnCode)) {
                    JSONArray arry = JSONArray.fromObject(jobj.get("object"));
                    List<PromptFile> lis = JSONArray.toList(arry, PromptFile.class);
                    logger.info("获取版本变化成功! :  "+lis);
                    return lis;
                }else{
                    logger.info("获取版本变化失败! : recutnCode 不等于0 !");
                    throw new Exception("获取版本变化失败! :  returnCode:"+returnCode);
                }
            } else {
                msg = URLDecoder.decode(conn.getResponseMessage(), "UTF-8");
                logger.info("resCode : "+resCode);
                throw new Exception("获取最新版本失败 : responseCode"+resCode+" returnMessage:"+msg);
            }
        } catch (IOException e) {
            throw new Exception("获取版本变化失败,连接业务运营系统失败", e);
        } finally {
            IOUtils.closeQuietly(reader);
            IOUtils.closeQuietly(is);
            if (conn != null) {
                conn.disconnect();
            }
        }
   

猜你喜欢

转载自blog.csdn.net/weixin_39372979/article/details/80612061
今日推荐