1.首先确定wsdl的http地址,使用postman测试接口是否成功
在浏览器输入webservice地址可以找到相应的请求和响应示例。
如果postman返回了正确的数据,就说明测试成功!文章来源:https://www.toymoban.com/news/detail-793773.html
2.接下来代码:文章来源地址https://www.toymoban.com/news/detail-793773.html
package com.test;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.json.XML;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Slf4j
@Service
/**
* @author "qs"
*/
public class webTest{
@Autowired
private RestTemplate restTemplate;
public void getData() {
HttpHeaders headers = new HttpHeaders();
MediaType type = MediaType.parseMediaType("text/xml;charset=UTF-8");
// 设置请求头对象contentTyp的为text/xml;charset=UTF-8
headers.setContentType(type);
StringBuffer soapRequestData = new StringBuffer("");
soapRequestData.append("<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/\">");
soapRequestData.append("<soap:Body>");
soapRequestData.append("<GetData xmlns=\"http://localhost/\" />");
soapRequestData.append("</soap:Body>");
soapRequestData.append("</soap:Envelope>");
String url = "你的地址";
String responseStr = exchangeForEntity(headers, soapRequestData + "", url, HttpMethod.POST, null);
String tmpStr = StringEscapeUtils.unescapeXml(responseStr);
if (StringUtils.isNotBlank(tmpStr)) {
org.json.JSONObject xmlJSONObj = null;
try {
xmlJSONObj = XML.toJSONObject(tmpStr);
} catch (JSONException e) {
e.printStackTrace();
}
if (xmlJSONObj != null) {
//处理数据
System.out.println(JSON.toJSONString(xmlJSONObj));
}
}
}
/**
* 执行http请求
*
* @param headers
* @param params
* @param url
* @param method
* @param mediaType
* @param <T> MultiValueMap<String, String> JSONObject Map
* @return
*/
public <T> String exchangeForEntity(HttpHeaders headers, T params, String url, HttpMethod method, MediaType mediaType) {
//设置请求头
if (mediaType != null) {
headers.setContentType(mediaType);
}
HttpEntity<T> requestEntity = new HttpEntity<>(params, headers);
// 执行HTTP请求
ResponseEntity<String> response = restTemplate.exchange(url, method, requestEntity, String.class);
return response.getBody();
}
}
到了这里,关于springboot使用restTemplate调用webservice接口的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!