Http和https的通信方法

HTTPS

 HttpsURLConnection httpsConn = null;
        URL url;
        try {
            String userName = PropertiesHolder.get("lnln.app.username");
            String password = PropertiesHolder.get("lnln.app.password");
            String host = PropertiesHolder.get("lnln.app.host");
            String uri = PropertiesHolder.get("lnln.app.uri");
            Authenticator.setDefault(new BasicAuthenticator(userName, password));
            String fullUrl = host + uri + appCheckHTTPDto.appUid + "/" + appCheckHTTPDto.subscribe;
            url = new URL(fullUrl);
            httpsConn = (HttpsURLConnection) url.openConnection();

            // レスポンスの取得.
            int responseCode = 0;
            String responseMsg = "";

            httpsConn.setRequestMethod("GET");
            String passId = new String(Base64.encodeBase64((userName + ":" + password).getBytes()));
            httpsConn.setRequestProperty("Authorization", "Basic " + passId);
            responseCode = httpsConn.getResponseCode();
            responseMsg = httpsConn.getResponseMessage();
            if (responseCode == 200) {
                if (!AppUserType.OK.toString().equals(responseMsg)) {
                    dto.addError(Errors.USER_NOT_IN_MEMBERSHIP);
                }
            } else {
                dto.addError(Errors.USER_NOT_IN_MEMBERSHIP);
            }
        } catch (Exception e) {
            e.printStackTrace();
            dto.addError(Errors.APP_MEMBER_CHECK_ERROR);
        }

HTTP

HttpURLConnection httpConn = null;
        URL url;
        try {
            String userName = PropertiesHolder.get("lnln.app.username");
            String password = PropertiesHolder.get("lnln.app.password");
            String host = PropertiesHolder.get("lnln.app.host");
            String uri = PropertiesHolder.get("lnln.app.uri");
            Authenticator.setDefault(new BasicAuthenticator(userName, password));
            String fullUrl = host + uri + appCheckHTTPDto.appUid + "/" + appCheckHTTPDto.subscribe;
            url = new URL(fullUrl);
            httpConn = (HttpURLConnection) url.openConnection();

            // レスポンスの取得.
            int responseCode = 0;
            String responseMsg = "";

            responseCode = httpConn.getResponseCode();
            responseMsg = httpConn.getResponseMessage();
            if (responseCode == 200) {
                if (!AppUserType.OK.toString().equals(responseMsg)) {
                    dto.addError(Errors.USER_NOT_IN_MEMBERSHIP);
                }
            } else {
                dto.addError(Errors.USER_NOT_IN_MEMBERSHIP);
            }
        } catch (Exception e) {
            e.printStackTrace();
            dto.addError(Errors.APP_MEMBER_CHECK_ERROR);
        }

HTTPS通信协议方式

System.setProperty("java.protocol.handler.pkgs", "javax.net.ssl");
        HostnameVerifier hv = new HostnameVerifier() {
            public boolean verify(String urlHostName, SSLSession session) {
                return urlHostName.equals(session.getPeerHost());
            }
        };

        HttpsURLConnection.setDefaultHostnameVerifier(hv);

        URL sslUrl;
        try {
            sslUrl = new URL("https://" + dto.host + dto.uri);

            httpsConn = (HttpsURLConnection) sslUrl.openConnection();

            httpsConn.setDoOutput(true);
            httpsConn.setRequestMethod("POST");
            httpsConn.setRequestProperty("Content-Type", dto.contentType);

            String passId = new String(Base64.encodeBase64((dto.loginID + ":" + dto.passWord).getBytes()));
            httpsConn.setRequestProperty("Authorization", "Basic " + passId);
            // 実データを書く
            OutputStreamWriter dos = new OutputStreamWriter(httpsConn.getOutputStream(), "Shift_JIS");
            // dos.write("\r\n");
            String args = "categoryid=" + dto.categoryid + "®check=" + dto.regcheck;
            if (dto.regcheck.equals("0")) {
                args = args + "&cid01=" + dto.cid;
            }
            args = args + "&testtype=" + dto.testType;
            dos.write(args);
            dos.flush();
            dos.close();

            // レスポンスの取得.
            int responseCode = 0;
            String responseMsg = "";

            responseCode = httpsConn.getResponseCode();
            responseMsg = httpsConn.getResponseMessage();

            if (responseCode == 200) {
                InputStream in = httpsConn.getInputStream();
                dto = this.getResponseInfo(in, dto);
                in.close();
                if (dto.result.equals("00")) {
                    sid = dto.calid;
                    httpsConn.disconnect();
                    return sid;
                }
            }
            throw new RuntimeException("responseCode:" + responseCode + " responseMsg:" + responseMsg + " result:" + dto.result + " detailCode:" + dto.detailCode);
        } catch (IOException e) {
            // 異常の場合
            throw new RuntimeException("スケジュールID取得する時、Http通信失敗");
        } finally {
            httpsConn.disconnect();
        }

 /**
     * レスポンスの取得.
     * @param input Input
     * @param dto DTO
     * @return ConcierScheduleHTTPDto
     * @throws IOException IOException
     */
    private ConcierScheduleHTTPDto getResponseInfo(InputStream input, ConcierScheduleHTTPDto dto) throws IOException {

        String responseData = "";
        String responseURLString = "";

        BufferedReader bReader = new BufferedReader(new InputStreamReader(input));

        while ((responseData = bReader.readLine()) != null) {
            responseData = responseData.trim();
            if (responseData.indexOf("=") != -1) {
                String[] responseArr = responseData.split("=");
                if (responseArr.length > 0) {
                    if (responseArr[0].equals("result")) {
                        dto.result = responseArr[1];
                    }
                    if (responseArr[0].equals("detailcode")) {
                        dto.detailCode = responseArr[1];
                    }
                    if (responseArr[0].equals("calid")) {
                        dto.calid = responseArr[1];
                    }
                }
            }
            responseURLString = responseURLString + responseData;
        }

        System.out.println(responseURLString);
        return dto;
    }

public ScheduleConcierResponseDto sendSchedule(ConcierScheduleDLDto dto, String fileName) {
        if (dto != null) {
            infoBoundary = PropertiesHolder.get("lnln.iconcier.schedule.boundary");
            infoHost = PropertiesHolder.get("lnln.iconcier.schedule.host");
            infoUri = PropertiesHolder.get("lnln.iconcier.schedule.uri");
            infoLoginId = PropertiesHolder.get("lnln.iconcier.schedule.loginId");
            infoLoginPass = PropertiesHolder.get("lnln.iconcier.schedule.loginPass");
            infoCategoryID = PropertiesHolder.get("lnln.iconcier.schedule.categoryID");
            infoCid = PropertiesHolder.get("lnln.iconcier.schedule.siteID");

            ScheduleConcierResponseDto scheduleConcierResponseDto = new ScheduleConcierResponseDto();

            System.setProperty("java.protocol.handler.pkgs", "javax.net.ssl");

            HostnameVerifier hv = new HostnameVerifier() {
                public boolean verify(String urlHostName, SSLSession session) {
                    return urlHostName.equals(session.getPeerHost());
                }
            };

            HttpsURLConnection.setDefaultHostnameVerifier(hv);
            URL sslUrl;
            try {
                sslUrl = new URL("https://" + infoHost + infoUri);
                HttpsURLConnection httpsConn = (HttpsURLConnection) sslUrl.openConnection();
                httpsConn.setDoOutput(true);

                // HTTPリクエストヘッダ.
                httpsConn.setRequestMethod("POST");
                httpsConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + infoBoundary);
                String passId = new String(Base64.encodeBase64((infoLoginId + ":" + infoLoginPass).getBytes()));
                httpsConn.setRequestProperty("Authorization", "Basic " + passId);

                String schFilePath = PropertiesHolder.get("lnln.iconcier.schFile.path") + fileName + ".vcs";
                File uidFile = new File(schFilePath);
                InputStreamReader fileDataIn = new InputStreamReader(new FileInputStream(uidFile), "Shift_JIS");

                String strDos = "";
                // 実データを書く
                OutputStreamWriter dos = new OutputStreamWriter(httpsConn.getOutputStream(), "Shift_JIS");
                // dos.write("\r\n");
                strDos = strDos + "--" + infoBoundary + "\r\n";
                strDos = strDos + "Content-Disposition: form-data; name=\"categoryid\"\r\n";
                strDos = strDos + "\r\n";
                strDos = strDos + infoCategoryID + "\r\n";
                strDos = strDos + "--" + infoBoundary + "\r\n";
                strDos = strDos + "Content-Disposition: form-data; name=\"kind\"\r\n";
                strDos = strDos + "\r\n";
                strDos = strDos + kind + "\r\n";
                strDos = strDos + "--" + infoBoundary + "\r\n";
                strDos = strDos + "Content-Disposition: form-data; name=\"updateday\"\r\n";
                strDos = strDos + "\r\n";
                strDos = strDos + updateDay + "\r\n";
                strDos = strDos + "--" + infoBoundary + "\r\n";
                strDos = strDos + "Content-Disposition: form-data; name=\"attachfile\"; " + "filename=\"" + fileName + ".vcs" + "\"" + "\r\n";
                strDos = strDos + "Content-Type: application/octet-stream\r\n\r\n"; // 改行を2回、つまり空白行を入れる.その後ファイルの実体を書く.

                dos.write(strDos);

                // ファイルの実体を書く
                int tmpBuff = 0;
                while ((tmpBuff = fileDataIn.read()) != -1) {
                    dos.write(tmpBuff);
                }

                // dos.write("\r\n");
                dos.write("\r\n--" + infoBoundary + "--\r\n");

                dos.flush();
                dos.close();
                fileDataIn.close();

                logger.info("****スケジュール配信電文  BEGIN****");
                strDos = strDos + "ファイルの実体を書く\r\n--" + infoBoundary + "--";

                logger.info(strDos);
                logger.info("****スケジュール配信電文  END****");

                // レスポンスの取得.
                int responseCode = 0;
                String responseMsg = "";

                responseCode = httpsConn.getResponseCode();
                responseMsg = httpsConn.getResponseMessage();
                logger.info("ResponseCode = " + responseCode);
                logger.info("ResponseMsg = " + responseMsg);

                if (responseCode == 200) {
                    InputStream in = httpsConn.getInputStream();
                    BeanUtils.copy(getResponseDto(in, responseCode), scheduleConcierResponseDto);
                    in.close();
                } else {
                    scheduleConcierResponseDto.statusCode = responseCode;
                }
                httpsConn.disconnect();

            } catch (Exception e) {
                mailerManagerFailure.sendErrMail("スケジュール配信エラー", "DOCOMOと通信中例外発生。メッセージ:" + e.getMessage());
                logger.error("DOCOMOと通信中エラー発生:" + e.getMessage());
            }
            return scheduleConcierResponseDto;
        }
        return null;
    }


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值