HttpClient调用WebService接口

前言

WebService是什么?

WebService即Web服务,它是一种跨编程语言和跨操作系统平台的远程调用技术。所谓跨编程语言和跨操作平台,就是说服务端程序采用Java编写,客户端程序则可以采用其他编程语言编写,反之亦然!跨操作系统平台则是指服务端程序和客户端程序可以在不同的操作系统上运行。

WebService原理?

客户端——> 阅读WSDL文档 (根据文档生成SOAP请求) ——>通过http调用发送到Web服务器——>交给WebService请求处理器 (ISAPI Extension)——>处理SOAP请求——> 调用WebService接口——>生成SOAP应答 ——> Web服务器通过http的方式返回客户端
在这里插入图片描述

HttpClient是什么?

HttpClient是Apache Jakarta Common 下的子项目,可以用来提供高效的、最新的、功能丰富的支持 HTTP 协议的客户端编程工具包,并且它支持 HTTP 协议最新的版本和建议

HttpClient应用场景?

  • 项目中需要与一个基于HTTP协议的第三方的接口进行对接
  • 项目中需要动态的调用WebService服务(不生成本地源码)
  • 项目中需要利用其它网站的相关数据

使用HttpClient调用WebService接口

1、创建HttpClient工具类

import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.HttpEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpClientUnit {
    //添加日志
    private static Logger logger = LoggerFactory.getLogger(HttpClientUnit.class);

    private final static String CONTENT_TYPE_TEXT_JSON = "text/json";
    
	public static String doPostSoap(String url, String soap, String SOAPAction) {
	        //请求体
	        String retStr = "";
	        // 创建HttpClientBuilder
	        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
	        // HttpClient
	        CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
	        HttpPost httpPost = new HttpPost(url);
	        try {
	            httpPost.setHeader("Content-Type", "text/xml;charset=UTF-8");
	            httpPost.setHeader("SOAPAction", SOAPAction);
	            StringEntity data = new StringEntity(soap,
	                    Charset.forName("UTF-8"));
	            httpPost.setEntity(data);
	            CloseableHttpResponse response = closeableHttpClient
	                    .execute(httpPost);
	            HttpEntity httpEntity = response.getEntity();
	            if (httpEntity != null) {
	                // 打印响应内容
	                retStr = EntityUtils.toString(httpEntity, "UTF-8");
	                System.err.println("response:" + retStr);
	            }
	            // 释放资源
	            closeableHttpClient.close();
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	        return retStr;
	    }

2、创建一个XML转JSON格式的工具类

因为HttpClient连接WebService服务的返回参数是xml类型的,而前端需要返回json类型,所有就要对结果进行转换

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 *  WebService服务工具类
 *  解析wsdl接口
 */
@Component
public class WebServiceUnit {

    /**
     * 解析webservice的返回结果
     * @param xmlStr xml内容
     * @return
     */
    public static JSONObject xml2Json(String xmlStr) throws DocumentException {
        Document doc = DocumentHelper.parseText(xmlStr);
        JSONObject json = new JSONObject();
        dom4j2Json(doc.getRootElement(), json);
        return json;
    }


    /**
     * xml转json
     * @param element
     * @param json
     */
    public static void dom4j2Json(Element element, JSONObject json) {
        List<Element> chdEl = element.elements();
        for(Element e : chdEl){
            if (!e.elements().isEmpty()) {
                JSONObject chdjson = new JSONObject();
                dom4j2Json(e, chdjson);
                Object o = json.get(e.getName());
                if (o != null) {
                    JSONArray jsona = null;
                    if (o instanceof JSONObject) {
                        JSONObject jsono = (JSONObject) o;
                        json.remove(e.getName());
                        jsona = new JSONArray();
                        jsona.add(jsono);
                        jsona.add(chdjson);
                    }
                    if (o instanceof JSONArray) {
                        jsona = (JSONArray) o;
                        jsona.add(chdjson);
                    }
                    json.put(e.getName(), jsona);
                } else {
                    if (!chdjson.isEmpty()) {
                        json.put(e.getName(), chdjson);
                    }
                }
            } else {
                if (!e.getText().isEmpty()) {
                    json.put(e.getName(), e.getText());
                }
            }
        }
    }
}

3、创建一个类,通过HttpClient工具类连接WebService服务

具体发送的参数和url在我的另一个文章里面有仔细的说明(第四步、发送xml的报文进行测试)https://blog.csdn.net/fuzhuangzhuang/article/details/113034418

@PostMapping("/GetLastDiagResultInfo")
    public JSONObject GetLastDiagResultInfo(@RequestBody QueryDiagResultInfoRequest request){
    	// 向WebService发送的参数格式(xml)
        String strParameter = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
                "<soapevn:Envelope xmlns:soapevn=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:util=\"http://util.com/\">\n" +
                "    <soapevn:Header/>\n" +
                "    <soapevn:Body>\n" +
                "        <util:QueryDiagResultInfo>\n" +
                "            <arg0>{\"pageIndex\":\""+request.getPageIndex()+"\",\"pageSize\":\""+request.getPageSize()+"\",\"type\":"+request.getType()+""</arg0>\n" +
                "        </util:QueryDiagResultInfo>\n" +
                "    </soapevn:Body>\n" +
                "</soapevn:Envelope>";
        // WebService服务的访问路径
        String url = "";
        // 向HttpClient发送请求
        String returnDatabase = HttpClientUnit.doPostSoap(url,strParameter,"");
        JSONObject jsonObject = null;
        try {
        	// 将请求结果转换成json类型
            jsonObject = WebServiceUnit.xml2Json(returnDatabase);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return jsonObject;
    }

4、使用postman访问本地路径测试

在这里插入图片描述

梦想也许在今天无法实现,但重要的是,它在你心里。重要的是,你一直在努力,加油!!!

在 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 接口为例,可以根据实际情况更改请求头信息和请求内容。此外,我们还需要处理响应。如果响应状态码为成功,我们可以解析出响应内容,并获取接口返回的结果。
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值