JDK发送Http请求

本文介绍了一个使用Java通过HTTP请求检查远程服务器上版本更新的方法。该方法通过POST请求发送客户端版本信息,从服务器获取最新的版本变更,并解析返回的JSON数据来确定是否有新的版本可用。若返回的returnCode为0,则认为获取版本变化成功。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


        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();
            }
        }
   
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值