[英]How to write file contents to a stream in java
我正在用JAX-WS API编写一个基本的Restful Web服务,您在其中提供城市名称,它为您提供最低和最高温度以及一些其他信息。
我正在从http://api.openweathermap.org/data/2.5/weather?q=singapore&mode=xml获得响应
@WebServiceProvider
@ServiceMode(value = javax.xml.ws.Service.Mode.MESSAGE)
@BindingType(value = HTTPBinding.HTTP_BINDING)
public class RESTfulWeather implements Provider<Source> {
@Resource
protected WebServiceContext wsContext;
@Override
public Source invoke(Source request) {
MessageContext msg_cxt = wsContext.getMessageContext();
String httpMethod = (String) msg_cxt
.get(MessageContext.HTTP_REQUEST_METHOD);
System.out.println("Http Method : " + httpMethod);
if (httpMethod.equalsIgnoreCase("GET")) {
doGet(msg_cxt);
}
return null;
}
private void doGet(MessageContext msg_cxt) {
String query_string = (String) msg_cxt.get(MessageContext.QUERY_STRING);
System.out.println("Request String : " + query_string);
try {
URL url = new URL(
"http://api.openweathermap.org/data/2.5/weather?q=singapore&mode=xml");
HttpURLConnection urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
BufferedReader bReader = new BufferedReader(new InputStreamReader(
urlConnection.getInputStream()));
String line = null;
String text="";
while ((line = bReader.readLine()) != null) {
System.out.println(line);
text=text+line;
}
System.out.println(text);
} catch (Exception e) {
e.printStackTrace();
}
}
}
这是出版商
public class WeatherPublisher {
public static void main(String[] args) {
System.out.println("Publishing Weather Service");
Endpoint.publish("http://127.0.0.1:8880/weather",new RESTfulWeather());
}
}
我确实在控制台中打印了xml,但是当我在浏览器中单击URL时,情况并非如此。
如何将xml提供给浏览器,如何将XML响应从天气服务写入浏览器
以下是控制台中打印的服务响应,我也希望在浏览器中
<?xml version="1.0" encoding="utf-8"?>
<current>
<city id="1880252" name="Singapore">
<coord lon="103.85" lat="1.29"/>
<country>SG</country>
<sun rise="2015-06-08T22:57:58" set="2015-06-09T11:09:41"/>
</city>
<temperature value="303.54" min="303.15" max="304.15" unit="kelvin"/>
<humidity value="66" unit="%"/>
<pressure value="1010" unit="hPa"/>
<wind>
<speed value="5.1" name="Gentle Breeze"/>
<direction value="260" code="W" name="West"/>
</wind>
<clouds value="75" name="broken clouds"/>
<visibility value="10000"/>
<precipitation mode="no"/>
<weather number="521" value="proximity shower rain" icon="09d"/>
<lastupdate value="2015-06-09T06:38:21"/>
</current>
在servlet的doGet中尝试
import static java.lang.System.out;
PrintWriter out = response.getWriter();
response.getWriter().println("text");
out.println( "text");
其中,响应为ServletResponse类型(或继承的HttpServletResponse类型)。 尝试从其他类调用此方法时,要么传递整个ServletResponse,要么传递从getWriter()返回的PrinterWriter作为变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.