首页 > 编程 > Java > 正文

java调用webservice-添加认证头(SOAPHeader)

2019-11-08 03:15:12
字体:
来源:转载
供稿:网友

 有时候有些 webservice的调用 服务端要求除了必要的参数以外  还需要通过认证头的认证  比如下面这一段

一种方式,通过 axis 来实现

/**	 * 获取axis请求形式的加密头	 * @return SOAPHeaderElement	 */	public SOAPHeaderElement getHoapHeader(){		Map<String,String> map = CacheKit.get("PageCache","signInfo");		if(map==null){			map = WebKit.getSignInfo();			CacheKit.put("PageCache","signInfo",map);		}		int thirdType = Integer.valueOf(map.get("thirdType"));		int secret1 = Integer.valueOf(map.get("secret1"));		String secret2 = map.get("secret2");				//上面代码为从缓存中取到我们需求传递到认证头的数据 下面开始添加认证头		SOAPHeaderElement head = new SOAPHeaderElement(new QName("http://www.hzsun.com/","SecurityHeader")); 		try {			SOAPElement a1 = head.addChildElement("ThirdType");		    a1.addTextNode(thirdType+""); 	        a1 = head.addChildElement("Secret1"); 	        a1.addTextNode(secret1+""); 	        a1 = head.addChildElement("Secret2"); 	        a1.addTextNode(secret2+""); 	        	        head.setPRefix("");		    head.setActor(null);		   //head.setMustUnderstand(true);		} catch (SOAPException e) {			e.printStackTrace();		}		return head; 	}public static Map<String,String> getSignInfo(){		Map<String,String> singInfoCache = new HashMap<String,String>();		try{		      // 指出service所在URL       		      String endpoint = "http://xxx.xxx.xx.xx/ThirdWebservice.asmx";  		      String targetNamespace = "http://www.hzsun.com/";		      String method="SignIn";		      		      // 创建一个服务(service)调用(call)       		      Service service = new Service();  		      Call call = (Call) service.createCall();// 通过service创建call对象       		      		      // 设置service所在URL       		      call.setTargetEndpointAddress(new java.net.URL(endpoint));  		      call.setOperationName(new QName(targetNamespace, method));		      call.setUseSOAPAction(true);	          Object ret = call.invoke(new Object[] {null});  	          System.out.println(ret.toString());	          Map<String,String> out = call.getOutputParams();	          if (out!=null){		           Iterator<Entry<String,String>> it = out.entrySet().iterator(); 		           while (it.hasNext()){			          	Entry<String,String> entry = (Entry<String,String>) it.next();  			          	Object key = entry.getKey();			          	String parm = key.toString().replace("{http://www.hzsun.com/}", "");			          	System.out.println("key:"+parm);			          	System.out.println("value:"+entry.getValue());			          	if("stanum".equalsIgnoreCase(parm)){			          		singInfoCache.put("nStaNum",entry.getValue().toString());			          	}else if("thirdType".equalsIgnoreCase(parm)){			          		singInfoCache.put("thirdType",entry.getValue().toString());			          	}else if("secret1".equalsIgnoreCase(parm)){			          		singInfoCache.put("secret1",entry.getValue().toString());			          	}else if("secret2".equalsIgnoreCase(parm)){			          		singInfoCache.put("secret2",entry.getValue().toString());			          	}		           }	          }		}catch(Exception e){			 e.printStackTrace();		}		return singInfoCache;	}

getHoapHeader()  拿到认证头后 完整的调用GetAccInfo 代码实现

public void getAccInfoByAxis(){		String sIDNo = getPara("sIDNo");		String nIDType = getParaToInt("nIDType",4).toString();		List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();		try{		      // 指出service所在URL       		      String endpoint = "http://xxx.xxx.xxx.xx/ThirdWebservice.asmx";  		      String targetNamespace = "http://www.hzsun.com/";		      String method="GetAccInfo";		      		      // 创建一个服务(service)调用(call)       		      Service service = new Service();  		      Call call = (Call) service.createCall();// 通过service创建call对象       		      		      // 设置service所在URL       		      call.setTargetEndpointAddress(new java.net.URL(endpoint));  		      call.setOperationName(new QName(targetNamespace, method));		      call.setUseSOAPAction(true);  		      call.setSOAPActionURI("http://www.hzsun.com/GetAccInfo");		      		      SOAPHeaderElement head = getHoapHeader();  //添加加密头验证加密因子		      call.addHeader(head);		      		      call.addParameter(new QName(targetNamespace,"sIDNo"),Constants.XSD_STRING,ParameterMode.IN);		      call.addParameter(new QName(targetNamespace,"nIDType"),Constants.XSD_INT,ParameterMode.IN);		      		      call.setReturnType(xmlType.XSD_STRING);	          Object ret = call.invoke(new Object[] {sIDNo,nIDType});  	          Map out = call.getOutputParams();	          if (out!=null)	          {	             Iterator ite=out.values().iterator();	             while (ite.hasNext())	             {	               // System.out.println("-------------"+(String)ite.next());					JSONObject jsonObject = JSONObject.fromObject((String)ite.next());  					//返回json数据解析					if (jsonObject.has("Table1")) {						JSONArray transitListArray = jsonObject.getJSONArray("Table1");						for (int i = 0; i < transitListArray.size(); i++) {			            	Map<String,Object> innerMap = new HashMap<String,Object>();			            	JSONObject obj = JSONObject.fromObject(transitListArray.get(i));			            	Iterator it = obj.entrySet().iterator();			            	while(it.hasNext()){			            		Entry entry = (Entry) it.next();  			            		innerMap.put(entry.getKey()+"",entry.getValue());			            	}			                dataList.add(innerMap);			            }					}	             }	          }		}catch(Exception e){			 e.printStackTrace();		}		renderJson(dataList);	}

第二种方式   直接发起http请求 拼接xml

同样以调用 GetAccInfo 为例

public String getSoapHeader(){		Map<String,String> map = CacheKit.get("PageCache","signInfo");		if(map==null){			map = WebKit.getSignInfo();			CacheKit.put("PageCache","signInfo",map);		}		int thirdType = Integer.valueOf(map.get("thirdType"));		int secret1 = Integer.valueOf(map.get("secret1"));		String secret2 = map.get("secret2");				//上面代码为从缓存中取到我们需求传递到认证头的数据 下面开始添加认证头		StringBuffer soapHeader = new StringBuffer();		soapHeader.append("<soap:Header>");		soapHeader.append("<SecurityHeader xmlns=/"http://www.hzsun.com//">");		soapHeader.append("<ThirdType>"+thirdType+"</ThirdType>");		soapHeader.append("<Secret1>"+secret1+"</Secret1>");		soapHeader.append("<Secret2>"+secret2+"</Secret2>");		soapHeader.append("</SecurityHeader>");		soapHeader.append("</soap:Header>");		return soapHeader.toString();	}

请求参数正文

public String getAccInfoXml(String sIDNo, int nIDType){		StringBuffer template = new StringBuffer();		String header = getSoapHeader();		template.append("<?xml version=/"1.0/" encoding=/"utf-8/"?><soap:Envelope xmlns:xsi=/"http://www.w3.org/2001/XMLSchema-instance/" xmlns:xsd=/"http://www.w3.org/2001/XMLSchema/" xmlns:soap=/"http://schemas.xmlsoap.org/soap/envelope//">");		template.append(header);		template.append("<soap:Body>");		template.append("<GetAccInfo xmlns=/"http://www.hzsun.com//">");		template.append("<sIDNo>"+sIDNo+"</sIDNo>");		template.append("<nIDType>"+nIDType+"</nIDType>");		template.append("</GetAccInfo>");		template.append("</soap:Body>");		template.append("</soap:Envelope>");		return template.toString();	}

完整调用
public void getAccInfo(){		String sIDNo = getPara("sIDNo");		int nIDType = getParaToInt("nIDType",4);		String dataJson = "";		List<Map<String, Object>> dataList = new ArrayList<Map<String, Object>>();		String urlStr = "http://xxxx.xxx.xxx.xx/ThirdWebservice.asmx";		String paraXml = getAccInfoXml(sIDNo, nIDType);		String soapAction ="http://www.hzsun.com/GetAccInfo";		OutputStream out = null;		try {			URL url = new URL(urlStr);			HttpURLConnection con;			con = (HttpURLConnection) url.openConnection();			con.setDoOutput(true);			con.setDoInput(true);			con.setRequestMethod("POST");			con.setUseCaches(false);			con.setRequestProperty("Content-type", "text/xml; charset=UTF-8");			//con.setRequestProperty("WSS-PassWord Type", "PasswordText");						con.setRequestProperty("SOAPAction", soapAction);			//con.setRequestProperty("Encoding", "UTF-8");			out = con.getOutputStream(); 			con.getOutputStream().write(paraXml.getBytes()); 			out.flush();		    out.close();		    int code = con.getResponseCode();		    String tempString = null;		    StringBuffer sb1 = new StringBuffer();		    if (code == HttpURLConnection.HTTP_OK) {		    	BufferedReader reader = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));			     while ((tempString = reader.readLine()) != null) {			      sb1.append(tempString);			     }			     if (null != reader) {			    	 reader.close();			     }		    } else {			     BufferedReader reader = new BufferedReader(new InputStreamReader(con.getErrorStream(), "UTF-8"));			     // 一次读入一行,直到读入null为文件结束			     while ((tempString = reader.readLine()) != null) {			      sb1.append(tempString);			     }			     if (null != reader) {			      reader.close();			     }		    }			    //响应报文		    	String respData=sb1.toString();				int startDataTag = respData.indexOf("<Data>");				int endDataTag = respData.indexOf("</Data>");				if(startDataTag!=-1&&endDataTag!=-1){					dataJson = respData.substring(respData.indexOf("<Data>")+6, respData.indexOf("</Data>"));					if(!"{Table1:[]}".equals(dataJson)){						JSONObject jsonObject = JSONObject.fromObject(dataJson);  						if (jsonObject.has("Table1")) {							JSONArray transitListArray = jsonObject.getJSONArray("Table1");							for (int i = 0; i < transitListArray.size(); i++) {				            	Map<String,Object> innerMap = new HashMap<String,Object>();				            	JSONObject obj = JSONObject.fromObject(transitListArray.get(i));				            	Iterator it = obj.entrySet().iterator();				            	while(it.hasNext()){				            		Entry entry = (Entry) it.next();  				            		innerMap.put(entry.getKey()+"",entry.getValue());				            	}				                dataList.add(innerMap);				            }						}					}				}else{					dataJson = respData;				}			    System.out.println("结束");		   } catch (Exception e) {   			   e.printStackTrace();		   } 		renderJson(dataList);	}


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表