http调用webservice

时间: 2023-08-15 admin 互联网

http调用webservice

http调用webservice

首先引用依赖pom

 <!-- 如果使用的是 springframework的RestTemplate发送http,那么需要引入此依赖-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<!-- 
		          使用apache的httpclient发送http,需要引入httpclient依赖;
		          使用OMElement需要引入axis2-transport-http依赖;改以来本身带有httpclient依赖,所以
		                 我们不在需要单独引入httpclient依赖了
		 -->
		<dependency>
			<groupId>org.apache.axis2</groupId>
			<artifactId>axis2-transport-http</artifactId>
			<version>1.7.8</version>
		</dependency>

		<dependency>
			<groupId>org.apache.httpcomponents</groupId>
			<artifactId>httpclient</artifactId>
			<version>4.5.6</version>
		</dependency>

		<!--  Xpath解析包-->
		<dependency>
			<groupId>jaxen</groupId>
			<artifactId>jaxen</artifactId>
			<version>1.1.6</version>
		</dependency>
		<dependency>
			<groupId>org.json</groupId>
			<artifactId>json</artifactId>
			<version>20170516</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>1.2.70</version>
		</dependency>
		<!--  -->
		<dependency>
			<groupId>dom4j</groupId>
			<artifactId>dom4j</artifactId>
			<version>1.6.1</version>
		</dependency>
</dependencies>

 

 

http请求这里用到了 工具类是 http请求webservice接口的工具类和获取到的数据xml转成json数据

package com;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.nio.charset.Charset;
import java.util.List;
/**
 * @ClassName HttpClientUnit
 * @Date 2021/5/18 10:50
 * @Author chengshoufei
 * @Description HttpClient调用WebService接口
 */
public class WSHttpClientUils {
	//添加日志
	static Logger log = LoggerFactory.getLogger(WSHttpClientUils.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);

			httpPost.getEntity();

			CloseableHttpResponse response = closeableHttpClient
					.execute(httpPost);
			HttpEntity httpEntity = response.getEntity();
			if (httpEntity != null) {
				// 打印响应内容
				retStr = EntityUtils.toString(httpEntity, "UTF-8");
			}
			// 释放资源
			closeableHttpClient.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return retStr;
	}


	/**
	 * @Date 2021/5/18 10:50
	 * @Author chengshoufei
	 * @Param [xmlStr]
	 * @return com.alibaba.fastjson.JSONObject
	 */
	public static JSONObject xml2Json(String xmlStr) throws DocumentException {
		Document doc = DocumentHelper.parseText(xmlStr);
		JSONObject json = new JSONObject();
		doParseXmlElements(doc.getRootElement() , json);
		return json;
	}
	/**
	 * @Date 2021/5/18 10:50
	 * @Author chengshoufei
	 * @Param [element, json]
	 * @return void
	 */
	public static void doParseXmlElements(Element element, JSONObject json) {
		List<Element> chdEl = element.elements();
		for(Element e : chdEl){
			if (!e.elements().isEmpty()) {
				JSONObject chdjson = new JSONObject();
				doParseXmlElements(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());
				}
			}
		}
	}
}

 

package com;



import com.alibaba.fastjson.JSONObject;
import org.dom4j.DocumentException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableScheduling;


@SpringBootApplication
@EnableScheduling

public class Application {
	static Logger log = LoggerFactory.getLogger(AbcAxis2DemoApplication.class);
	public static void main(String[] args) {
		SpringApplication.run(AbcAxis2DemoApplication.class, args);
		User user=new User();
		user.setMyName("张三");
		user.setMyAge(121);
		user.setMyMotto("6666");
		user.setMypice(123);
		StringBuffer soapRequestParams = new StringBuffer();
		soapRequestParams.append("<soapenv:Envelope xmlns:soapenv=\"/\" xmlns:ser=\"/\">");
		soapRequestParams.append("<soapenv:Header/>");
		soapRequestParams.append("<soapenv:Body>");
		soapRequestParams.append("<ser:userMethod>");
		soapRequestParams.append("<name>"+user.getMyName()+"</name>");
		soapRequestParams.append("<age>"+user.getMyAge()+"</age>");
		soapRequestParams.append("<motto>"+user.getMyMotto()+"</motto>");
		soapRequestParams.append("<pice>"+user.getMypice()+"</pice>");
		soapRequestParams.append("</ser:userMethod>");
		soapRequestParams.append("</soapenv:Body>");
		soapRequestParams.append("</soapenv:Envelope>");
		log.info("soapRequestParams============          "+soapRequestParams.toString());
     // 从配置文件调用WebService服务的访问路径
		StringBuilder url = new StringBuilder();
		url.append("http://");
		url.append(HttpUrlConfig.HOST);
		url.append(":");
		url.append(HttpUrlConfig.PORT);
		url .append("/");
		url.append("webservice/test");
		log.info("url路径=========      "+url.toString());
		//url 请求路径 soapRequestParams.toString() 请求体(请求参数 )   向HttpClient发送请求
		String returnDatabase = WSHttpClientUils.doPostSoap(url.toString() , soapRequestParams.toString(),"");
		log.info("returnDatabase============       "+returnDatabase);
		JSONObject jsonObject=null;
		try {
			//通过工具类 xml 转出 json
			 jsonObject = WSHttpClientUils.xml2Json(returnDatabase);
		  //解析json
		    JSONObject body = jsonObject.getJSONObject("Body");
		    JSONObject userMethod = body.getJSONObject("userMethodResponse");
		    log.info("json数据格式化============       "+userMethod);
		} catch (DocumentException e) {
			e.printStackTrace();
		}
	}
}