生活随笔
收集整理的这篇文章主要介绍了
Webservice调用天气接口案例
小编觉得挺不错的,现在分享给大家,帮大家做个参考.
废话不多说,希望能够帮助到大家。
天气接口: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;
public class Test {public static void main(String[] args
) throws DocumentException {post();}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");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
;}public static JSON xmlToJson(String xml
) throws DocumentException {List list
= new ArrayList<>();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
;}
}
总结
以上是生活随笔为你收集整理的Webservice调用天气接口案例的全部内容,希望文章能够帮你解决所遇到的问题。
如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。