调用Http外部接口,请求xml格式,接收解析xml数据

一、依赖包

需要导入dom4j包
下载地址:🛫飞机路径

二、实列方法以及思路

/** 调用外部接口*/
	@Test
	public void analysisXml(){
		String xml = getHttpProductApi();
		try {
			//将xml转编码 如果不转有可能出现乱码
			xml = new String(xml.getBytes("GBK"), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		try {
			Document document = DocumentHelper.parseText(xml);
			// 转编码
			document.setXMLEncoding("utf-8");
			//获取到最大的节点   Request
			Element root = document.getRootElement();
			//获取    Header  的节点信息
			Element header = root.element("Header");
			//获取    ProductResponse 商品响应数据
			Element productResponse = root.element("ProductResponse");
			//获取多个相同子节点
			Iterator otherInfo = productResponse.elementIterator("OtherInfo");
			while (otherInfo.hasNext()){
				// 获取相同第一个标签
				Element itemEle = (Element) otherInfo.next();
				// 获取标签属性值
				List<DefaultAttribute> attributes1 = itemEle.attributes();
				for (DefaultAttribute attr : attributes1){
					System.out.println(itemEle.getName()+":[ nodeName:"+attr.getName()+"   nodeValue:"+ attr.getStringValue()+"  stringValue:"+itemEle.getText()+"]\n");
				}
			}

		//		String SourceSystem = header.elementText("SourceSystem");
		//		String MessageID = header.elementText("MessageID");
		//
		//		//获取    Body--->CT_MedicineMaterialList--->CT_MedicineMaterial  的节点信息
		//		Element body = root.element("Body").element("CT_MedicineMaterialList").element("CT_MedicineMaterial");


		} catch (DocumentException e) {
			e.printStackTrace();
		}

	}

	// 请求xml参数
	public String getHttpProductApi(){
		String url = ".....";
		String xmlHeader=
				"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
				"<PriceAvailabilityRequest>\n" +
				"\t<Header>\n" +
				"\t\t<MessageId>WUXIAPPTEC-2021-11-08 13:25:15.072</MessageId>\n" +
				"\t\t<Timestamp>2021-11-08 13:25:15.072</Timestamp>\n" +
				"\t</Header>\n" +
				"\t<RequesterInfo>\n" +
				"\t\t<Customer code=\"WUXIAPPTEC_PACN\"/>\n" +
				"\t\t<Location code=\"CN\"/>\n" +
				"\t\t<PreferredLanguage>EN</PreferredLanguage>\n" +
				"\t\t<PreferredCountry>CN</PreferredCountry>\n" +
				"\t</RequesterInfo> \n" +
				"\t\t<ProductRequest itemNumber=\"1\"> \n" +
				"\t\t\t<SupplierPartNumber>195030-100ML</SupplierPartNumber> \n" +
				"\t\t\t<UnitOfMeasure unit=\"\"/> \n" +
				"\t\t\t<Quantity>1</Quantity> \n" +
				"\t\t</ProductRequest>\n" +
				"</PriceAvailabilityRequest>";
		String returnMsg = post(url, xmlHeader);
		System.out.println(returnMsg);
		return returnMsg;
	}

// 请求外部接口POST
	public String post(String url, String xmlFileName) {
		//关闭
		System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
		System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
		System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "stdout");

		//创建httpclient工具对象
		HttpClient client = new HttpClient();
		//创建post请求方法
		PostMethod myPost = new PostMethod(url);
		//设置请求超时时间
		client.setConnectionTimeout(300 * 1000);
		String responseString = null;
		try {
			//设置请求头部类型
			myPost.setRequestHeader("Content-Type", "text/xml");
			myPost.setRequestHeader("charset", "utf-8");

			//设置请求体,即xml文本内容,注:这里写了两种方式,一种是直接获取xml内容字符串,一种是读取xml文件以流的形式
			// 1.xml文本内容
			myPost.setRequestBody(xmlFileName);
			// 2.xml文件
//			InputStream body = this.getClass().getResourceAsStream("/" + xmlFileName);
//			myPost.setRequestBody(body);
			//            myPost.setRequestEntity(new StringRequestEntity(xmlString,"text/xml","utf-8"));
			int statusCode = client.executeMethod(myPost);
			if (statusCode == HttpStatus.SC_OK) {
				BufferedInputStream bis = new BufferedInputStream(myPost.getResponseBodyAsStream());
				byte[] bytes = new byte[1024];
				ByteArrayOutputStream bos = new ByteArrayOutputStream();
				int count = 0;
				while ((count = bis.read(bytes)) != -1) {
					bos.write(bytes, 0, count);
				}
				byte[] strByte = bos.toByteArray();
				responseString = new String(strByte, 0, strByte.length, "utf-8");
				bos.close();
				bis.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		myPost.releaseConnection();
		return responseString;
	}

在这里插入图片描述

如果报错:java.io.FileNotFoundException: 项目路径\xxx.xx (系统找不到指定的文件。)

在项目路径下加缺少的文件

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值