http与https的写法

1.http与https服务端写法是一样的

比如

/***
 *
 * 测试服务端
 *
 */
public class YunOpenServiceImpl extends HttpServlet {

    private static final long serialVersionUID = 3075928223335310013L;

    private Logger logger = LoggerFactory.getLogger(getClass());
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        if(req.isSecure()){
            
        }
        // 读取Http Body中的数据信息
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/x-www-form-urlencoded");
        PrintWriter out = resp.getWriter();
        ServletInputStream sis = req.getInputStream();
        BufferedReader reader = null;
        reader = new BufferedReader(new InputStreamReader(sis, "UTF-8"));
        String s = "";
        StringBuffer query = new StringBuffer();
        while ((s = reader.readLine()) != null) {
            query.append(s.trim());
        }
        String xml = query.toString();
        System.out.println(xml);
        
        Document doc = null;
        try {
            doc = DocumentHelper.parseText(xml);
            Element rootElt = doc.getRootElement(); // 获取根节点
            System.out.println("根节点:" + rootElt.getName()); // 拿到根节点的名称
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        
        String msg = "";
        msg += "<SalesOrderRequestModel>"
                + "<RequestGuid>111111</RequestGuid>"
                + "<RequestTimeStamp>111111</RequestTimeStamp>"
                + "<Status>Success</Status>"
                + "<ResponseMessage>Say something here.</ResponseMessage>"
                + "<ErrorCode></ErrorCode>"
                + "<HasError></HasError>"
                +"<SalesOrders>"
              
                                + "<Tax>"
                                        + "<Version>V1</Version>"
                                        + "<IsTaxIncluded>false</IsTaxIncluded>"
                                        + "<TaxRate>0</TaxRate>"
                                        + "<TaxAmount>0</TaxAmount>"
                                + "</Tax>"
                    
                        +"</SalesOrders>"
                        + "</SalesOrderRequestModel>";
            
        // 输出响应消息
        out.println(msg);
        out.flush();
        out.close();
        //更新响应接口日志
        //updateInterfaceLog(resJson,log,param);
    }

===============web.xml配置=========================================================================

<servlet>
        <servlet-name>YunOpenServiceImpl</servlet-name>
        <servlet-class>com.hongguaninfo.hgdf.webservice.yunSetList.service.YunOpenServiceImpl</servlet-class>
    </servlet>
 
    <servlet-mapping>
        <servlet-name>YunOpenServiceImpl</servlet-name>
        <url-pattern>/YunOpenServiceImpl</url-pattern>
    </servlet-mapping>


===================web.xmlhttps 配置==================================


<!-- 浏览器必须使用https访问 -->
     <login-config>
     <!-- Authorization setting for SSL -->
    <auth-method>CLIENT-CERT</auth-method>
    <realm-name>Client Cert Users-only Area</realm-name>
    </login-config>
    <security-constraint>
    <!-- Authorization setting for SSL -->
    <web-resource-collection >
    <web-resource-name >SSL</web-resource-name>
     <url-pattern>/*</url-pattern>
     </web-resource-collection>
     <user-data-constraint>
    <transport-guarantee>CONFIDENTIAL</transport-guarantee>
   </user-data-constraint>
     </security-constraint>


========================web.xml如果访问dao和service层=====================================


public class IsvListener implements ServletContextListener {
    
    public static TbCustOrderDao tbCustOrderDao;
    
    public static TbPrdCustDao TbPrdCustDao;
    
    public static DbIdGenerator dbIdGenerator;
    
    public static TbAssetDao tbAssetDao;
    
    public static OrderPrdPriceDao orderPrdPriceDao;
    
    public static InterfaceLogDao interfaceLogDao;
    
    
    public static SysUserRoleJoinDao sysUserRoleJoinDao;

    public static SysUserDao sysUserDao;
    
    public static SysUserService sysUserService;
    
    public static SysRoleDao sysRoleDao;
    
    public static TbCustOrderService tbCustOrderService;

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        ApplicationContext ac = WebApplicationContextUtils
                .getRequiredWebApplicationContext(sce.getServletContext());
        tbCustOrderDao=(TbCustOrderDao) ac.getBean("tbCustOrderDao");
        TbPrdCustDao=(TbPrdCustDao) ac.getBean("TbPrdCustDao");
        dbIdGenerator=(DbIdGenerator) ac.getBean("dbIdGenerator");
        tbAssetDao=(TbAssetDao) ac.getBean("tbAssetDao");
        orderPrdPriceDao=(OrderPrdPriceDao) ac.getBean("orderPrdPriceDao");
        interfaceLogDao=(InterfaceLogDao) ac.getBean("interfaceLogDao");
        sysUserRoleJoinDao=(SysUserRoleJoinDao) ac.getBean("sysUserRoleJoinDao");
        sysUserDao=(SysUserDao) ac.getBean("sysUserDao");
        sysUserService=(SysUserService) ac.getBean("sysUserService");
        sysRoleDao=(SysRoleDao)ac.getBean("sysRoleDao");
        tbCustOrderService=(TbCustOrderService) ac.getBean("tbCustOrderService");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        // TODO Auto-generated method stub
    }
    
}

============================TOMCAT配置看一下上一篇转载的博客=其实很简单=======================




===================================客户端的写法===红色是https要用到的=其他都是http要用到的==============================




public class YunOpenClientService {
    protected static Log logger = LogFactory.getLog(YunOpenClientService.class);;
    final static String getYunserviceopen_url= propertyWebservice.getYunserviceopen_url();
        @Autowired
        private OrderPrdPriceDao orderPrdPriceDao;
         
        @Autowired
        private JdbcTemplate jdbcTemplate;
    
        public Boolean openYun(int orderId) throws IOException, Exception {
            OrderPrdPrice orderPrdPrice = orderPrdPriceDao.getOrderPrdPriceByYun(orderId);
            UUID uuid = UUID.randomUUID();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
            Date date = new Date();
            String strDate=sdf.format(date);
              //单价
               String cost=orderPrdPrice.getCost();
               double c=Long.valueOf(cost);
               int b=100;
               double co1=c/100;
             String co=  new java.text.DecimalFormat("0.00").format(co1);
               //总金额
               String totalAmount=orderPrdPrice.getPrice();
               double total=Long.valueOf(totalAmount);
               double to1=total/100;
               String to= new java.text.DecimalFormat("0.00").format(to1);
               //折扣
              String discount= orderPrdPrice.getDiscount();
              double disc=Long.valueOf(discount);
              double di=disc/100;
            String xml = "";
            xml += "<SalesOrderRequestModel>"
                    + "<ChannelId>学校</ChannelId>"
                    + "<RequestGuid>"+uuid+"</RequestGuid>"
                    + "<RequestTimeStamp>"+strDate+"</RequestTimeStamp>"
                    + "<ActionCode>PlaceOrder</ActionCode>"
                    + "<SalesOrder>"
                            + "<AuthProvider>MPSS</AuthProvider>"
                            + "<AuthUserId>mpss@ctwamp.com</AuthUserId>"
                           
                                    + "<Tax>"
                                            + "<Version>V1</Version>"
                                            + "<IsTaxIncluded>false</IsTaxIncluded>"
                                            + "<TaxRate>0</TaxRate>"
                                            + "<TaxAmount>0</TaxAmount>"
                                    + "</Tax>"
                            + "</SalesOrder>"
                            + "</SalesOrderRequestModel>";
            System.out.println("====================好好哈哈"+xml);
            logger.info(orderId+"云产品开通"+xml);
            byte[] data = xml.getBytes();
             SSLContext sc = SSLContext.getInstance("SSL");
                sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },
                  new java.security.SecureRandom());

            
              
            URL url = new java.net.URL(getYunserviceopen_url);
            HttpPost httppost = new HttpPost(getYunserviceopen_url);
            // 配置要 POST 的数据begin
             // MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
                 HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
            HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
              conn.setSSLSocketFactory(sc.getSocketFactory());
              conn.setHostnameVerifier(new TrustAnyHostnameVerifier());

            conn.setRequestMethod("POST");
            
            conn.setConnectTimeout(500 * 1000);
            conn.setReadTimeout(2000 * 1000);
            conn.setDoOutput(true);
            conn.setRequestProperty("Content-Type", "text/xml;charset=UTF-8");
            conn.setRequestProperty("Content-Length", "156");
            OutputStream outStream = conn.getOutputStream();// 返回写入到此连接的输出流
            outStream.write(data);
            outStream.close();//关闭流
            String msg = "";// 保存调用http服务后的响应信息
            // 如果请求响应码是200,则表示成功
            if (conn.getResponseCode() == 200) {
                // HTTP服务端返回的编码是UTF-8,故必须设置为UTF-8,保持编码统一,否则会出现中文乱码
                BufferedReader in = new BufferedReader(new InputStreamReader(
                        (InputStream) conn.getInputStream(), "UTF-8"));
                msg = in.readLine();
                in.close();
            }
            conn.disconnect();// 断开连接
            Document doc = null;
            String status = "notOK";
      
          logger.info(orderId+"云产品开通响应"+msg);
            String SalesOrderId="";
            try {
                doc = DocumentHelper.parseText(msg);
                Element rootElt = doc.getRootElement(); // 获取根节点
                System.out.println("Status: " + rootElt.elementText("Status"));
          
                if(StringUtil.isNotEmpty(status)){
                    status = rootElt.elementText("Status");
                    SalesOrderId=rootElt.element("SalesOrders").element("SalesOrder").elementText("SalesOrderId");
    
                }
            } catch (DocumentException e) {
            
                e.printStackTrace();
            }
            
            Boolean message;
            if(status.equals("Success")){
                jdbcTemplate.update("update TB_CUST_ORDER set MP_SIGN=1,SalesOrderId='"+SalesOrderId+"' where ORDER_ID="+orderId);
                message = true;
            }else{
                message = false;
            }
            return message;
        }
        
        
        private class TrustAnyTrustManager implements X509TrustManager {
              public void checkClientTrusted(X509Certificate[] chain, String authType)
                         throws CertificateException {
                       }
                       public void checkServerTrusted(X509Certificate[] chain, String authType)
                         throws CertificateException {
                       }
                       public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[] {};
                       }
                       
                
        }
        
        private class TrustAnyHostnameVerifier implements HostnameVerifier{
             public boolean verify(String hostname, SSLSession session) {
                    return true;
                   }
        }



        
}




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值