废话不多说,希望能够帮助到大家。
天气接口:http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl
pom.xml配置:
com.sun.jersey
jersey-client
1.18
compile
com.alibaba
fastjson
1.2.24
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.api.client.config.DefaultClientConfig;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import javax.ws.rs.core.MediaType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Description TOO
* @Date 2022/8/3 0003 16:43
*/
public class Test {
public static void main(String[] args) throws DocumentException {
post();
}
/**
*功能描述 :调用天气接口
* @date 2022/8/3 0003
* @param
* @return java.lang.String
*/
public static String post() throws DocumentException {
//创建客户端
Client client = Client.create(new DefaultClientConfig());
//指定资源
WebResource webResource = client.resource("http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl");//外网
//path:请求的方法,entity请求的参数,type请求的格式,post请求方式(返回的类型)
ClientResponse clientResponse = webResource.path("getSupportCity").entity("byProvinceName=湖南").type(MediaType.APPLICATION_FORM_URLENCODED).post(ClientResponse.class);
String xml = clientResponse.getEntity(String.class);
System.out.println(xmlToJson(xml));
System.out.println(xml);
return xml;
}
/**
*功能描述 :将返回的xml转化为json
* @author LKY
* @date 2022/8/3 0003
* @param
*/
public static JSON xmlToJson(String xml) throws DocumentException {
List list = new ArrayList<>();
//将xml格式的字符串转换成Document对象
Document doc = DocumentHelper.parseText(xml);
//获取根节点
Element root = doc.getRootElement();
//获取根节点下的所有元素
List children = root.elements();
//循环所有子元素
if(children != null && children.size() > 0) {
for(int i = 0; i < children.size(); i++) {
Map map1 = new HashMap();
Element child = (Element)children.get(i);
map1.put(child.getName(), child.getTextTrim());
list.add(map1);
}
}
JSONArray jsonObject1 = (JSONArray) JSONObject.toJSON(list);
return jsonObject1;
}
}