Dict.CN 在线词典, 英语学习, 在线翻译

都市淘沙者

荔枝FM Everyone can be host

统计

留言簿(23)

积分与排名

优秀学习网站

友情连接

阅读排行榜

评论排行榜

HttpURLConnection常用处理方式

/*
 * Classname       : GameSoapProcessor
 * Create Date     : 2008-5-7
 
*/

package cn.allinpalm.sns.app.web.mxt.game;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.hibernate.HibernateException;

import cn.allinpalm.sns.app.wirelessapi.HttpSend;
import cn.allinpalm.sns.app.web.filter.HibernateFilter;

/**
 * 处理从游戏服务商接收到的SOAP消息
 * 
 * 
@author   lqm
 * 
@version  1.0
 
*/

public class SoapMsgProcessorServlet extends HttpServlet {
    
    
private static final long serialVersionUID = 1L;
    
private static Logger log = Logger.getLogger(SoapMsgProcessorServlet.class);
    
    
public SoapMsgProcessorServlet() {}

    
public void doPost(HttpServletRequest request, HttpServletResponse response) {

        OutputStream out 
= null;
        
try {
            request.setCharacterEncoding(
"UTF-8");
            Document doc 
= null;
            doc 
= new SAXReader().read(request.getReader());
            log.info(doc.asXML());
            
            
/*保存从soap消息包到数据库中*/
            GameUser user 
= setSoapMsgBean(doc);
            String issaveok 
= saveSoapMoMsg(setSoapMsgBean(doc));        
            String restr 
= retOptRespPkg(setSoapMsgBean(doc),issaveok);
            
            out 
= response.getOutputStream();
            out.write(restr.getBytes(
"UTF8"));
            out.flush();

        }
 catch (IOException e) {
            log.error(e, e);
        }
 catch (Exception e) {
            log.error(e, e);
        }

        
finally{
            
if(out!=null){
                
try{
                    out.close();
                }
catch(IOException e){
                    log.error(e, e);
                }

               
            }

        }

    }

    
    
public void doGet(HttpServletRequest request, HttpServletResponse response)
            
throws ServletException,
                IOException 
{
        doPost(request, response);
    }

    
    
    
public GameUser setSoapMsgBean(Document doc) {
        
       GameUser bean 
= new GameUser();            
       Element root 
= doc.getRootElement();
       
       
for ( Iterator iter = root.elementIterator(); iter.hasNext(); ) {
             Element element 
= (Element) iter.next();
           
if(element.getName().equals("Body")) 
               Element MOReqelement
=element.element("MOReq");
               
//遍历MOReq结点的所有孩子节点,并进行处理
               for ( Iterator iterInner = MOReqelement.elementIterator(); iterInner.hasNext(); ) {
                    Element elementInner 
= (Element) iterInner.next();
                  
//  hm.put(elementInner.getName(), elementInner.getText());
                    if("Msg_Id".equals(elementInner.getName()))
                        bean.setMsgid(elementInner.getText());
                    }

                    
if("Src_terminal_Id".equals(elementInner.getName()))
                        bean.setSrcterminalid(elementInner.getText());
                    }

                    
if("Dest_Id".equals(elementInner.getName()))
                        bean.setDestid(elementInner.getText());
                    }

                    
if("MsgContent".equals(elementInner.getName()))
                        bean.setMsgcontent(elementInner.getText());
                    }

                    
if("LinkID".equals(elementInner.getName()))
                        bean.setLinkid(elementInner.getText());
                    }

                    
if("CreateDate".equals(elementInner.getName()))
                        bean.setCreatedate(elementInner.getText());
                    }

                    
//System.out.println("elementInner.getName()="+elementInner.getName()+"---=="+elementInner.getText());
               }

           }

       }
 

        
return bean;
    }

    
    
/**
     * 保存是否成功 isok为1表示失败,为0表示成功
     * 
@param msgbean
     * 
@return
     
*/

    
public String  saveSoapMoMsg(GameUser msgbean){
        
        String isok 
= "1";
        PreparedStatement stmt
=null;
        String sql 
= "insert into maintain.gameuserlog(id,msgseq_id,srcterm_id,dest_id,msg_content,linkid,create_date,add_date)" +
                
" values(maintain.GAME_USER_LOG_SEQ.Nextval,?,?,?,?,?,?,sysdate)";
        
        
try {
            stmt 
= HibernateFilter.getSession().connection().prepareStatement(sql);
            stmt.setString(
1, msgbean.getMsgid() );
            stmt.setString(
2, msgbean.getSrcterminalid());
            stmt.setString(
3, msgbean.getDestid());
            stmt.setString(
4, msgbean.getMsgcontent());
            stmt.setString(
5, msgbean.getLinkid());
            stmt.setString(
6, msgbean.getCreatedate());
            stmt.executeUpdate();
            HibernateFilter.getSession().connection().commit();
            
            isok 
= "0";
        }
 catch (HibernateException e) {
            e.printStackTrace();
        }
 catch (SQLException e) {
            e.printStackTrace();
        }
finally{
            
if (stmt != null)
            
{
                
try {
                    stmt.close();
                }
 catch (SQLException e) {
                    
// TODO Auto-generated catch block
                    e.printStackTrace();
                }

            }
   
        }

        
return isok;        
    }

    
    
/**
     * 操作返回响应包
     * 
@param userid
     * 
@return
     
*/

    
public static String  retOptRespPkg(GameUser user,String flag){
        
        StringBuffer sb 
= new StringBuffer();
        sb.append(
"<?xml version = \"1.0\"  encoding=\"UTF-8\" ?>\r\n");
        sb.append(
"<SOAP-ENV:Envelope\r\n");
        sb.append(
"xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'\r\n");      
        sb.append(
"xmlns:xsd='http://www.w3.org/2001/XMLSchema'\r\n");  
        sb.append(
"xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/'\r\n");        
        sb.append(
"xmlns:SOAP-ENC='http://schemas.xmlsoap.org/soap/encoding/' >\r\n");                  
        sb.append(
"<SOAP-ENV:Header>\r\n");
        sb.append(
"</SOAP-ENV:Header>\r\n");       
        sb.append(
"<SOAP-ENV:Body>\r\n");    
        sb.append(
"<MOResp xmlns='http://www.infuns.com/IFXML/IFXMLSchema.xsd/'>\r\n");       
        sb.append(
"<Msg_Id>"+user.getMsgid()+"</Msg_Id>\r\n");
        sb.append(
"<LinkID>"+user.getLinkid()+"</LinkID>\r\n");
        sb.append(
"<hRet>"+flag+"</hRet><!-- 接收解析成功:0; 接收解析失败:1;-->\r\n");
        sb.append(
"</MOResp>\r\n");      
        sb.append(
"</SOAP-ENV:Body>\r\n"); 
        sb.append(
"</SOAP-ENV:Envelope>");  
        
        
return sb.toString();
    }
 
    

    
    
/**
      * 遍历整个XML文件,获取所有节点的值与其属性的值,并放入HashMap中
      * 
@param filename String 待遍历的XML文件(相对路径或者绝对路径)
      * 
@param hm       HashMap 存放遍历结果,格式:<nodename,nodevalue>或者<nodename+attrname,attrvalue>
      
*/

     
public static void iterateWholeXML(){
         
      HashMap
<String,String> hm = new HashMap<String,String>();
      SAXReader saxReader 
= new SAXReader();
      
try {
           Document document 
= saxReader.read(new File("D:\\code\\trunk_lxw\\lxwSrc\\cn\\allinpalm\\sns\\app\\web\\mxt\\game\\test.xml"));
           Element root 
= document.getRootElement();

           
for ( Iterator iter = root.elementIterator(); iter.hasNext(); ) {
                 Element element 
= (Element) iter.next();
               
if(element.getName().equals("Body")) 
                   Element MOReqelement
=element.element("MOReq");
                   
//遍历MOReq结点的所有孩子节点,并进行处理
                   for ( Iterator iterInner = MOReqelement.elementIterator(); iterInner.hasNext(); ) {
                        Element elementInner 
= (Element) iterInner.next();
                        hm.put(elementInner.getName(), elementInner.getText());
                        System.out.println(
"elementInner.getName()="+elementInner.getName()+"---=="+elementInner.getText());
                   }

               }

           }

      }
 catch (DocumentException e) {
       
// TODO Auto-generated catch block
       e.printStackTrace();
      }

     }


     
    
public static void main(String[] args) {
        
//iterateWholeXML();
        StringBuffer sb = new StringBuffer();
        sb.append(
"<?xml version = \"1.0\"  encoding=\"UTF-8\" ?>\r\n");
        sb.append(
"<SOAP-ENV:Envelope\r\n");
        sb.append(
"xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'\r\n");      
        sb.append(
"xmlns:xsd='http://www.w3.org/2001/XMLSchema'\r\n");  
        sb.append(
"xmlns:SOAP-ENV='http://schemas.xmlsoap.org/soap/envelope/'\r\n");        
        sb.append(
"xmlns:SOAP-ENC='http://schemas.xmlsoap.org/soap/encoding/' >\r\n");                  
        sb.append(
"<SOAP-ENV:Header>\r\n");
        sb.append(
"</SOAP-ENV:Header>\r\n");       
        sb.append(
"<SOAP-ENV:Body>\r\n");    
        sb.append(
"<MOReq xmlns='http://www.infuns.com/IFXML/IFXMLSchema.xsd/'>\r\n");       
        sb.append(
"<Msg_Id>2e5fb10009610029</Msg_Id>\r\n");
        sb.append(
"<Dest_Id>33000015</Dest_Id>\r\n");
        sb.append(
"<Src_terminal_Id>15810912222</Src_terminal_Id>\r\n");
        sb.append(
"<MsgContent>YXBY15 07M003155 IF5</MsgContent>\r\n");        
        sb.append(
"<LinkID>23590311470360662046</LinkID>\r\n");
        sb.append(
"<CreateDate>2006-08-01 00:00:00.000</CreateDate>\r\n");
        sb.append(
"</MOReq>\r\n");      
        sb.append(
"</SOAP-ENV:Body>\r\n"); 
        sb.append(
"</SOAP-ENV:Envelope>"); 
           
        log.info(HttpSend.connectURL(
"http://localhost:6060/SoapMsgProcessorServlet",sb.toString()));

    }

    
    
}


public class HttpSend {
    
    
private static Logger log = Logger.getLogger(HttpSend.class);
    
    
public static String connectURL(String dest_url, String commString)
    
{
        log.debug(
"send data to Url:"+dest_url);
        String rec_string 
= "";
        URL url 
= null;
        OutputStream out 
= null;
        BufferedReader rd 
= null;
        HttpURLConnection urlconn 
= null;
        
try
        
{
            url 
= new URL(dest_url);
            urlconn 
= (HttpURLConnection) url.openConnection();
            urlconn.setReadTimeout(
5000);
            urlconn.setRequestProperty(
"content-type""text/plain");
            urlconn.setRequestMethod(
"POST");
            urlconn.setDoInput(
true);
            urlconn.setDoOutput(
true);
            out 
= urlconn.getOutputStream();
            out.write(commString.getBytes(
"UTF8"));
            out.flush();
            out.close();
            rd 
= new BufferedReader(new InputStreamReader(
                    urlconn.getInputStream()));
            StringBuffer sb 
= new StringBuffer();
            
int ch;
            
while ((ch = rd.read()) > -1){
//                System.out.println(ch);
                sb.append((char) ch);
            }

            rec_string 
= sb.toString();
            log.info(
"resp="+rec_string);
            rd.close();
            urlconn.disconnect();
        }

        
catch (Exception e)
        
{
            log.error(e, e);
            
return "";
        }
finally {
            
try {
                
if (out != null{
                    out.close();
                }

                
if (urlconn != null{
                    urlconn.disconnect();
                }

                
if (rd != null{
                    rd.close();
                }

            }
 catch (Exception e) {
                log.error(e, e);
            }

        }


        
return rec_string;
    }


}

posted on 2008-05-09 13:25 都市淘沙者 阅读(1189) 评论(0)  编辑  收藏 所属分类: Java Basic/Lucene/开源资料


只有注册用户登录后才能发表评论。


网站导航: