如何在Servlet中调用RESTfulAPIWeb服务
假设我们需要搜索并显示指定城市的天气情况。互联网上有很多第三种Web服务。我正在使用百度天气Web服务进行演示。现在,让我们开始以下步骤。
使用代码转到您选择使用Web服务的网站,然后注册一个帐户并为您获取一个apikey。查找并了解API描述。以百度为例。API地址:http://apis.baidu.com/heweather/weather/free请求方法:GET标头中的请求参数:名称类型必需的地点描述默认值apikeystring是的标头您的Web服务提供商提供的APIkeyapikey网址参数:名称类型必需的地点描述默认值citystring是的urlParamcity namebeijing结果在杰森:"HeWeather data service 3.0": [{ "status": "ok", //status, "basic": { //basic info "city": "Beijing", //city name "cnty": "China", //country "id": "CN101010100", //city id "lat": "39.904000", //latitude of city "lon": "116.391000", //longitude of city "update": { //update time "loc": "2015-07-02 14:44", //locate time "utc": "2015-07-02 06:46" //UTC time } }, "now": { // the weather at this time "cond": { //weather condition "code": "100", //weather condition code "txt": "sunny day" //weather condiftion description },,...... //Omitted }]}1234567891011121314151617181920212223复制代码类型:[java] 为了轻松测试RESTAPI。请在您的计算机上找到或安装一些工具,例如restclient,fiddler等。如果您使用的是Chrome或Firefox浏览器,则还可以安装REST客户端加载项。我在Chrome浏览器上安装了AdvancedRESTClient。启动其余客户端。请输入下图所示的API地址和apikey,然后单击“发送”按钮。您将得到一个jsonstring结果。
启动http://www.jsonschema2pojo.org/万维网。jsonschema2pojo.org/并复制json字符串结果并将其粘贴到页面中以生成javabean类。在Eclipse中创建动态Web项目后,请下载该zip并将其解压缩到您的项目文件夹中。
使用Eclipse打开项目时,将看到以下图像:
为服务(例如com.BaiduWeather.Services)创建一个新程序包。在此处找到调用RESTfullAPI的代理。在其中添加一个名为BaiduWeatherService.java的类,并在其下面添加代码行。注意事项:在此之前,您应该从MavenCentral的GsonDownload下载gson-2.8.0.jar,将其复制到WebContent/WEB-INF/lib/gson-2.8.0.jar文件夹中,然后将其添加到JavaBuildPath中。记住要用您的apiKey进行更改。package com.BaiduWeather.Services;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;import java.io.UnsupportedEncodingException;import java.net.HttpURLConnection;import java.net.MalformedURLException;import java.net.URL;import java.net.URLEncoder;import com.BaiduWeather.Entities.Root;import com.google.gson.Gson;import com.google.gson.GsonBuilder;import com.google.gson.JsonSyntaxException;/** * baidu weather service */public class BaiduWeatherService { private static final String apiKey="0ae09eed4f3c024451ads12d1gsgsg1sg";//change this with yours private static final String baseBaiduUrl= "http://apis.baidu.com/heweather/weather/free?city=";//The constant url should be //stored in config file public static Root getWeatherInfo(String cityName) { String jsonResult=getWeatherJsonString(cityName); Root weatherInfoObject=toEntity(jsonResult); return weatherInfoObject; } //Covert json string to class object private static Root toEntity(String jsonString) { try{ Gson gson = new GsonBuilder().create(); Root weatherInfo = gson.fromJson(jsonString, Root.class); return weatherInfo; } catch(JsonSyntaxException ex) { ex.printStackTrace(); return null; } } //Get the weather of the specific city private static String getWeatherJsonString(String cityName) throws RuntimeException{ //define a variable to store the weather api url and set beijing as it's default value String baiduUrl = baseBaiduUrl+"beijing"; //default value hard-coded 'beijing' //should be stored in config file try { if(cityName!=null && cityName!="") baiduUrl = baseBaiduUrl+URLEncoder.encode(cityName, "utf-8"); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); } StringBuilder strBuf = new StringBuilder(); HttpURLConnection conn=null; BufferedReader reader=null; try{ //Declare the connection to weather api url URL url = new URL(baiduUrl); conn = (HttpURLConnection)url.openConnection(); conn.setRequestMethod("GET"); conn.setRequestProperty("Accept", "application/json"); conn.setRequestProperty("apikey",apiKey); if (conn.getResponseCode() != 200) { throw new RuntimeException("HTTP GET Request Failed with Error code : " + conn.getResponseCode()); } //Read the content from the defined connection //Using IO Stream with Buffer raise highly the efficiency of IO reader = new BufferedReader(new InputStreamReader(conn.getInputStream(),"utf-8")); String output = null; while ((output = reader.readLine()) != null) strBuf.append(output); }catch(MalformedURLException e) { e.printStackTrace(); }catch(IOException e){ e.printStackTrace(); } finally { if(reader!=null) { try { reader.close(); } catch (IOException e) { e.printStackTrace(); } } if(conn!=null) { conn.disconnect(); } } return strBuf.toString(); }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107复制代码类型:[java] 创建一个新包,com.BaiduWeather.Servlets并在其下创建一个新类WeatherServlet.java。在此Java文件中添加以下代码行:package com.BaiduWeather.Servlets;import java.io.IOException;import java.util.List;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import com.BaiduWeather.Entities.HeWeatherDataService30;import com.BaiduWeather.Entities.Root;import com.BaiduWeather.Services.BaiduWeatherService; /** * Servlet implementation class WeatherServlet * * We can use 。jsp instead of servlet */@WebServlet("/weather")public class WeatherServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public WeatherServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Get weather json info and convert it to object String city=request.getParameter("city"); Root wheatherInfoObject=BaiduWeatherService.getWeatherInfo(city); if(wheatherInfoObject!=null){ List<HeWeatherDataService30> weatherlist= wheatherInfoObject.getHeWeatherDataService30(); if(weatherlist!=null) { //output the weather content on web page. StringBuilder outputContent=new StringBuilder();//Unless the need of thread-safe, //Use StringBuilder not StringBuffer,because the latter takes more erformance overhead because of Synchronization //More cities can be store in a database or file,then load them into an array,then generators options of selection here outputContent.append("<!DOCTYPE html><html><head><meta charset=\"UTF-8\"> <title>Insert title here</title></head><body><form action=\"weather\" method=\"GET\"><select name=\"city\"><option value =\"beijing\">北京</option> <option value =\"shanghai\">上海</option><option value =\"xian\">西安</option> </select><input type=\"submit\" value=\"Submit\"></form>"); outputContent.append(weatherlist.get(0).getBasic().getCity()); outputContent.append("<br/>"); outputContent.append(weatherlist.get(0).getNow().getTmp()); outputContent.append("℃"); outputContent.append("<br/>"); outputContent.append(weatherlist.get(0).getNow().getCond().getTxt()); outputContent.append("<br/>"); outputContent.append(weatherlist.get(0).getNow().getWind().getDir()); outputContent.append("</body></html>"); response.setContentType("text/html; charset=utf-8"); response.getWriter().write(outputContent.toString()); } } } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677复制代码类型:[java] 在WebContent/WEB-INF/web.xml中,添加以下配置项。<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>BaiduWeather</display-name> <welcome-file-list> <!-- <welcome-file>index.html</welcome-file> --> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> <welcome-file>weather</welcome-file> </welcome-file-list> <servlet> <!-- class name --> <servlet-name>WeatherServlet</servlet-name> <!-- package--> <servlet-class>com.BaiduWeather.Servlets.WeatherServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>WeatherServlet</servlet-name> <!-- address --> <url-pattern>/BaiduWeather/weather</url-pattern> </servlet-mapping> </web-app>123456789101112131415161718192021222324252627复制代码类型:[java] 运行并调试该servlet,您应该在HTML页面上获取天气信息。