1. 程式人生 > >java向webService介面(.net)傳送請求並接收返回資料

java向webService介面(.net)傳送請求並接收返回資料

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.css.apps.base.dict.service.DictMan;

public class sendHttp {

    private static Log log = LogFactory.getLog(sendHttp .class);
    public static Map<String, List<String>> a = new HashMap<String, List<String>>();
    public static List<String> nodeNameList = new ArrayList<>();
    
    public static Map sendHttpTest(String loginName,String flag,String number) throws IOException {
    	Map c = new HashMap();
        //第一步:建立服務地址,不是WSDL地址 
    	String urlstr = DictMan.getDictType("yh_interface_firstpage", "6").getName();
        URL url = new URL(urlstr);  
        //第二步:開啟一個通向服務地址的連線  
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();  
        //第三步:設定引數  
        //3.1傳送方式設定:POST必須大寫  
        connection.setRequestMethod("POST");
        //3.2設定資料格式:content-type  
        connection.setRequestProperty("content-type", "text/xml;charset=utf-8");   
        //3.3設定輸入輸出,因為預設新建立的connection沒有讀寫許可權,  
        connection.setDoInput(true);  
        connection.setDoOutput(true);
        //第四步:組織SOAP資料,傳送請求  
        //判斷是否是全區會議通知還是我的會議通知
        String soapXML = null;
	soapXML = getXMLRegionMeetingNotice(loginName,number);
        OutputStream os = connection.getOutputStream();  
        os.write(soapXML.getBytes()); 
 
        //第五步:接收服務端響應,列印(xml格式資料)
        int responseCode = connection.getResponseCode();  
        if(200 == responseCode){//表示服務端響應成功
            InputStream is = null;
            InputStreamReader isr = null;
            BufferedReader br = null;
            StringBuilder sb = null;
            try {
                is = connection.getInputStream();  
                isr = new InputStreamReader(is);  
                BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                sb = new StringBuilder();  
                String temp = null;  
                while(null != (temp = br.readLine())){  
                    sb.append(temp);  
                }
            	c = convertXmlToMap(sb.toString());

            } catch (Exception e) {
                e.printStackTrace();
                throw e;
            } finally {
                br.close();
                isr.close();
                is.close();
            }
        }  
        os.close();
		return c;
    }
  	
    /**
	 * xml報文轉換為map
	 * @author lpx
	 */
    
	public static Map<String, List<String>> convertXmlToMap(String xmldata){
		Map<String, List<String>> map=new HashMap<String, List<String>>();
	    Document doc=null;
	    try {
	    	//將字串轉換為doc
			doc=DocumentHelper.parseText(xmldata);
			//獲取根節點
			Element root=doc.getRootElement();
			map=getNodes(root);
			nodeNameList = new ArrayList<>();
		} catch (Exception e) {
			e.printStackTrace();
		}
	  
		return map;
		
	}
	
    /** 
     * 從指定節點Element node開始,遞迴遍歷其所有子節點 
     */  
    @SuppressWarnings("unchecked")
	public static Map<String, List<String>> getNodes(Element node) {
        // 當前節點的名稱、文字內容和屬性  
        String nodeName = node.getName();// 當前節點名稱  
        String nodeText = node.getTextTrim();// 當前節點內容
       //節點名為messageText加入map中去
       if(!node.getTextTrim().isEmpty() && "messageText".equals(nodeName)){
    	   nodeNameList.add(nodeText);
    	   a.put("messageText",nodeNameList);
       }
       // 遞迴遍歷當前節點所有的子節點  
        final List<Element> listElement = node.elements();// 所有一級子節點的list  
        for (final Element e : listElement) {// 遍歷所有一級子節點  
            getNodes(e);// 遞迴
        }
        return a;  
    } 
    public static String getXMLRegionMeetingNotice(String loginName,String number){  
    	String _xmlInfo = "<soap:Envelope xmlns:soap=\"http://www.w3.org/2003/05/soap-envelope\" xmlns:tem=\"http://tempuri.org/\">"
			 	+ "<soap:Header/>"
			 	+ "<soap:Body>"
			 	+ "<tem:GetQqHytz>"
			 	+ "<tem:xmlDoc>"
			 	+ "<Root>"
			 	+ "<Document>"
			 	+ "<LoginName>"
			 	+ loginName
			 	+ "</LoginName>"
			 	+ "<Number>"
			 	+ number
			 	+ "</Number>"
			 	+ "</Document>"
			 	+ "</Root>"
			 	+ "</tem:xmlDoc>"
			 	+ "</tem:GetQqHytz>"
			 	+ "</soap:Body>"
			 	+ "</soap:Envelope>" ;
        return _xmlInfo;  
    }  
}
    

​感謝某位博主寫的博文,這裡面僅僅起到記載作用,但是那位博文因為瀏覽器清快取,地址找不到了。。。。。┓(;´_