HttpClient调用webservice接口案例

本文详细介绍了一种使用Java的HttpClient库实现SOAP客户端调用WebService的方法。通过具体代码示例,展示了如何构造SOAP请求,包括设置请求头、请求体及参数,以及如何解析返回的SOAP响应结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.rzx.base.utils;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.InputStreamRequestEntity;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.RequestEntity;


 /**
  * SOAP客户端工具类
  * @author Administrator
  *
  */
public class HttpClientCallWSUtil extends WriteLogUtils {
	
	/**
	 * 
	 * @param wsdl wsdl地址
	 * @param ns 命名空间
	 * @param method 方法名
	 * @param list 查收列表
	 * @param result  是否需要返回结果
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("null")
	public synchronized static String accessService(String wsdl, String ns, String method, List<String> list, String result) throws Exception {
		
		 StringBuffer stringBuffer = new StringBuffer();
		 //拼接参数
		 for(int i=0;i<list.size();i++){
			 stringBuffer.append("<arg" + i + ">" + list.get(i) + "</arg" + i + ">");
		 }
		 String soapReponseDatea = "";
		 //拼接SOAP
		 StringBuffer soapRequestData = new StringBuffer("");
		 soapRequestData.append("<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:ser=\""+ns+"\">");
		 //soapRequestData.append(ns);
		 soapRequestData.append("<soapenv:Header/>");
		 soapRequestData.append("<soapenv:Body>");
		 soapRequestData.append("<ser:" + method + ">");
		 soapRequestData.append(stringBuffer);
		 soapRequestData.append("</ser:" + method + ">");
		 soapRequestData.append("</soapenv:Body>" + "</soapenv:Envelope>");
		 
		 writeLog("com.rzx.base.utils.HttpClientCallWSUtil","********传递参数"+soapRequestData.toString()+"****");
		 
		 PostMethod postMethod = new PostMethod(wsdl);
		 //将Soap请求数据添加到postMethod中
		 byte[] b = null;
		 InputStream is = null;
		 try{
			 b = soapRequestData.toString().getBytes("utf-8");
			 is = new ByteArrayInputStream(b, 0, b.length);
			 RequestEntity re = new InputStreamRequestEntity(is, b.length, "text/xml; charset=UTF-8");
			 postMethod.setRequestEntity(re);
			 HttpClient httpClient = new HttpClient();
			 int status = httpClient.executeMethod(postMethod);
			 if(status == 200){
				 soapReponseDatea = getMesage(postMethod.getResponseBodyAsString(),result);
			 }
		 }catch(Exception e){
			 e.printStackTrace();
		 }finally{
			 if(is==null){
				 is.close();
			 }
			 
		 }
		 
		return soapReponseDatea;
	}

	/**
	 * 处理返回结果
	 * @param responseBodyAsString
	 * @param result
	 * @return
	 */
	private static String getMesage(String soapAttachment, String result) {
		if(result == null){
			return null;
		}
		if(soapAttachment!=null&&soapAttachment.length()>0){
			int begin = soapAttachment.indexOf("<return>");
			begin = soapAttachment.indexOf(">", begin);
			int end = soapAttachment.indexOf("</return>");
			String str = soapAttachment.substring(begin+1, end);
			str = str.replaceAll("<", "<");
			str = str.replaceAll(">", ">");
			return str;
		}else{
		return null;
		}
	}
	
	//参数处理
	public static String getParam(Map<String,String> params){
		String param = "";
		if(params!=null){
			Iterator<String> iterator = params.keySet().iterator();
			while(iterator.hasNext()){
				String str = iterator.next();
				param +="<"+str+">";
				param +=params.get(str);
				param +="</"+str+">";
			}
		}
		return param;
	}
	
	
	/**
	 * 测试 用例
	 * @param args
	 */
	public static void main(String[] args) {
		try{
            
            doCallFyysPortalcal();
			
		}catch(Exception e ){
			e.printStackTrace();
		}
	}

public String doCallFyysPortalcal(){

		HttpClientCallWSUtil httpClientCallWSUtil = new HttpClientCallWSUtil();
		
		String wsdl="http://10.10.105.52:9999/basic/fyysWebservice";
		
		
		String ns = "http://impl.rzx.webservice.nctooa.com/";//名称空间可以在wsdl文件中获取
		
		String method="callBill2NCSync";
		List<String> list=new ArrayList<String>();
		list.add("param1");
		list.add("param2");
		list.add("param3");
		String result="result";
		try {
			String callResult = httpClientCallWSUtil.accessService(wsdl, ns, method, list, result);
			
			//处理成功
			return callResult;
		} catch (Exception e) {
			e.printStackTrace();
			//调用异常记录日志
		}
		
		return "null";
	}
}

如上的wsdl文件可以在http://ws-addr?wsdl中获取

 

如何使用客户端调用webservice发布的服务(客户端工具)

打开webservice studio

 

第二种方法 :

/**
	 * 调用NC
	 */
	@Override
	public String syncOAdept2NC() throws Exception {
		List<OaDeptcodeEntiry> syncDataList = findAllDeptData();
		if(syncDataList==null||syncDataList.size()==0) return "获取部门数据为空!";
		//校验重复
		List<String> deptCodes1 = new ArrayList<String>();
		for (OaDeptcodeEntiry oaDeptcodeEntiry : syncDataList) {
			String departmentcode = oaDeptcodeEntiry.getDepartmentcode();
			if(StringUtils.isEmpty(departmentcode))continue;
			deptCodes1.add(departmentcode);
		}
		
		Set<String> setCodes = new HashSet<String>();
		for (String deptCode : deptCodes1) {
			setCodes.add(deptCode);
		}
		
		if(deptCodes1==null||deptCodes1.size()==0)return "没有可以同步的数据!";
		if(deptCodes1.size()!=setCodes.size()) return "部门编码存在重复,请检查数据库!";
		
		String syncJsonData = JSON.toJSONString(syncDataList);
		System.out.println(syncJsonData);
		StringBuffer sb = new StringBuffer();
		 sb.append("<soap:Envelope xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"> \r\n");
		 sb.append(" <soap:Body> \r\n");
		 sb.append("  <syncBasicData xmlns=\"http://service.basic.data.rzx.com.cn/DataSyncPortocalService\"> \r\n");
		 sb.append("  <string xmlns=\"\">1</string> \r\n");
		 sb.append("   <string1 xmlns=\"\">"+Base64Utils.encode(syncJsonData)+"</string1> \r\n");
		 sb.append("    </syncBasicData> \r\n");
		 sb.append("   </soap:Body> \r\n");
		 sb.append("   </soap:Envelope> \r\n");
		String rs = null;
		try {
			@SuppressWarnings("deprecation")
			HttpClient httpClient = new DefaultHttpClient();
			HttpPost post = new HttpPost(ApplicationConfig.NC_Url + "/uapws/service/DataSyncPortocalService");
			StringEntity postingString = new StringEntity(sb.toString());// json传递
			post.setEntity(postingString);
			// post.setHeader("Content-type", "text/xml;charset=UTF-8");
			HttpResponse response = httpClient.execute(post);
			rs = EntityUtils.toString(response.getEntity());
			//System.out.println(rs);
			if (rs != null && rs.contains("<return>success</return>")) {
				return null;
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			return "发生了错误 ,原因:" + ex.getMessage();
		}
		if (rs == null) {
			return "请求为空!";
		}
		if (!(rs.contains("<return>") && !rs.contains("</return>"))) {
			return "处理结果:" + rs.substring(rs.indexOf("<return>"), rs.indexOf("</return>"));
		}
		return rs.substring(rs.indexOf("<return>"), rs.indexOf("</return>"));
	
	}

	
	

该案例的名称空间通过如下方式获取

 

在 C# 中使用 `HttpClient` 调用 WebService 接口的方法如下: 1. 首先需要添加 `System.Net.Http` 和 `System.Web.Services` 引用。 2. 在代码中创建 `HttpClient` 实例,并设置请求头信息和请求内容。 ```csharp using System; using System.Net.Http; using System.Threading.Tasks; using System.Xml; namespace ConsoleApp1 { class Program { static async Task Main(string[] args) { // 创建 HttpClient 实例 HttpClient httpClient = new HttpClient(); // 设置请求头信息 httpClient.DefaultRequestHeaders.Add("SOAPAction", "http://tempuri.org/HelloWorld"); // 设置请求内容 string soapRequest = @"<?xml version=""1.0"" encoding=""utf-8""?> <soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/""> <soap:Body> <HelloWorld xmlns=""http://tempuri.org/"" /> </soap:Body> </soap:Envelope>"; HttpContent httpContent = new StringContent(soapRequest, System.Text.Encoding.UTF8, "text/xml"); // 发送请求 HttpResponseMessage httpResponse = await httpClient.PostAsync("http://localhost:8080/HelloWorldService.asmx", httpContent); // 处理响应 if (httpResponse.IsSuccessStatusCode) { string soapResponse = await httpResponse.Content.ReadAsStringAsync(); XmlDocument xmlDoc = new XmlDocument(); xmlDoc.LoadXml(soapResponse); string result = xmlDoc.GetElementsByTagName("HelloWorldResult")[0].InnerText; Console.WriteLine($"调用成功,返回结果:{result}"); } else { Console.WriteLine($"调用失败,响应状态码:{httpResponse.StatusCode}"); } } } } ``` 上述代码以调用 HelloWorld 接口为例,可以根据实际情况更改请求头信息和请求内容。此外,我们还需要处理响应。如果响应状态码为成功,我们可以解析出响应内容,并获取接口返回的结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值