生活随笔
收集整理的這篇文章主要介紹了
Webservice调用天气接口案例
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
廢話不多說,希望能夠幫助到大家。
天氣接口: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
;}
}
總結(jié)
以上是生活随笔為你收集整理的Webservice调用天气接口案例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。