欢迎大家来到IT世界,在知识的湖畔探索吧!
Web Service 定义
Web Service也称为 XML Web Service, WebService是一种可以接收从Internet或者Intranet上的其它系统中传递过来的请求数据,轻量级的独立的通讯技术。是通过SOAP在Web上提供的软件服务,使用WSDL文件进行说明,并通过UDDI进行注册。WebService是一种跨平台语言和跨操作系统平台的远程调用的技术。
作为java软件工程师都知道有时候我们需要调用第三方平台接口,很多接口语言协议不统一很是头痛。今天我们用三种方式来调用天气的接口作为案例来讲解。
我们直接访问天气接口返回一个界面提供了四种方法说明:
1.SOAP 1.2 请求和响应示例
package com.gwu.test;import cn.hutool.json.JSONArray;import cn.hutool.json.XML;import com.alibaba.fastjson.JSON;import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.io.OutputStream;import java.net.HttpURLConnection;import java.net.URL;import java.util.List;public class TestXmlWebService { /** * 发送http post调用webservice * * @param strUrl * @param requestSoapXml * @return * @throws IOException */ public static String soapPost(String strUrl, String requestSoapXml) throws IOException { //第一步:创建服务地址,不是WSDL地址pp URL url = new URL(strUrl); //第二步:打开一个通向服务地址的连接 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); //第三步:设置参数 //3.1发送方式设置:POST必须大写 connection.setRequestMethod("POST"); //3.2设置数据格式:content-type connection.setRequestProperty("content-type", "text/xml;charset=utf-8"); //3.3设置输入输出,因为默认新创建的connection没有读写权限, connection.setDoInput(true); connection.setDoOutput(true); //请求头必须设置SOAPAction connection.setRequestProperty("SOAPAction","http://WebXml.com.cn/getWeatherbyCityName"); //第四步:组织SOAP数据,发送请求 OutputStream os = connection.getOutputStream(); os.write(requestSoapXml.getBytes()); //第五步:接收服务端响应,打印 int responseCode = connection.getResponseCode(); StringBuilder sb = new StringBuilder(); if (200 == responseCode) {//表示服务端响应成功 InputStream is = connection.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); String temp = null; while (null != (temp = br.readLine())) { sb.append(temp); } is.close(); isr.close(); br.close(); }else{ throw new RuntimeException("调用webservice失败:服务器端返回HTTP code " + responseCode + "信息:" ); } os.close(); return sb.toString(); } public static void main(String[] args) { String url = "http://www.webxml.com.cn/WebServices/WeatherWebService.asmx"; String p = "<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">\n" + " <soap:Body>\n" + " <getWeatherbyCityName xmlns=\"http://WebXml.com.cn/\">\n" + " <theCityName>广州</theCityName>\n" + " </getWeatherbyCityName>\n" + " </soap:Body>\n" + "</soap:Envelope>"; try{ String response = TestXmlWebService.soapPost(url,p); cn.hutool.json.JSONObject data = XML.toJSONObject(response); //从data中解析rescode和resmsg,其中"rescode"为0时代表成功,其他均为失败。 JSONArray resMsg = data.getJSONObject("soap:Envelope") .getJSONObject("soap:Body") .getJSONObject("getWeatherbyCityNameResponse") .getJSONObject("getWeatherbyCityNameResult") .getJSONArray("string"); String resMsgStr= JSON.toJSONString(resMsg); List<String> list=com.alibaba.fastjson.JSONArray.parseArray(resMsgStr,String.class); for ( String a: list) { System.out.println(a); } }catch (Exception e){ e.printStackTrace(); } }}
欢迎大家来到IT世界,在知识的湖畔探索吧!
2.HTTP GET 请求和响应示例
欢迎大家来到IT世界,在知识的湖畔探索吧!package com.gwu.test;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.XML;
import com.alibaba.fastjson.JSON;
import com.gwu.utils.HttpUtil;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
@Slf4j
public class TestGetWebService {
public static void main(String[] args) {
String result = HttpUtil.sendGet("http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getWeatherbyCityName?theCityName=广州");
cn.hutool.json.JSONObject data = XML.toJSONObject(result);
JSONObject jsonObject = data.getJSONObject("ArrayOfString");
JSONArray lastjSONArray = jsonObject.getJSONArray("string");
String mes = JSON.toJSONString(lastjSONArray);
List<String> list = com.alibaba.fastjson.JSONArray.parseArray(mes, String.class);
for (String as : list
) {
System.out.println(as);
}
}
/**
* 发送GET方法的请求
*/
public static String sendGet(String url) {
String result = "";
BufferedReader in = null;
try {
URL realUrl = new URL(url);
//打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// HttpURLConnection connection = (HttpURLConnection) realUrl.openConnection();
//设置属性
setGetProperty(connection);
//建立实际的连接
connection.connect();
//获取所有响应头字段
Map<String, List<String>> map = connection.getHeaderFields();
//遍历所有的响应头字段
for (String key : map.keySet()) {
log.info(key + "===>" + map.get(key));
}
//定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(
connection.getInputStream(), "UTF-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
log.info("发送GET请求出现异常!" + e);
e.printStackTrace();
}
//使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* get方法请求属性设置
*/
private static void setGetProperty(URLConnection connection) {
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
}
}
3.HTTP POST 请求和响应示例
下面提供java post调用实例 关键要注意设置head信息
package com.gwu.test;import cn.hutool.json.JSONArray;import cn.hutool.json.JSONObject;import cn.hutool.json.XML;import com.alibaba.fastjson.JSON;import lombok.extern.slf4j.Slf4j;import org.apache.http.HttpEntity;import org.apache.http.client.entity.UrlEncodedFormEntity;import org.apache.http.client.methods.CloseableHttpResponse;import org.apache.http.client.methods.HttpPost;import org.apache.http.impl.client.CloseableHttpClient;import org.apache.http.impl.client.HttpClients;import org.apache.http.message.BasicNameValuePair;import org.apache.http.util.EntityUtils;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;@Slf4jpublic class TestPostWebService {public static void main(String[] args) {String url="http://www.webxml.com.cn/WebServices/WeatherWebService.asmx/getWeatherbyCityName"; Map<String, String> headerMap=new HashMap<>(); headerMap.put("Content-Type", "application/x-www-form-urlencoded; charset=utf-8"); headerMap.put("accept", "*/*"); headerMap.put("connection", "Keep-Alive"); headerMap.put("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)"); Map<String, String> bodyMap=new HashMap<>(); bodyMap.put("theCityName", "广州"); String resultStr= sendFormPost( url, headerMap, bodyMap); JSONObject data = XML.toJSONObject(resultStr); JSONObject jsonObject= data.getJSONObject("ArrayOfString"); JSONArray lastString=jsonObject.getJSONArray("string"); String result= JSON.toJSONString(lastString); List<String> list=com.alibaba.fastjson.JSONArray.parseArray(result,String.class); for ( String as: list) {System.out.println(as); }}/** * 发送form表单类型的Post请求 * * @param url 发送的url * @param headerMap 请求头参数集合 key参数名 value为参数值 * @param bodyMap 请求参数集合 key参数名 value为参数值 */ public static String sendFormPost(String url, Map<String, String> headerMap, Map<String, String> bodyMap) {//创建post请求对象 HttpPost post = new HttpPost(url); try {//创建参数集合 List<BasicNameValuePair> list = new ArrayList<>(); //添加参数 if (bodyMap != null) {for (String str : bodyMap.keySet()) {list.add(new BasicNameValuePair(str, bodyMap.get(str))); }}//把参数放入请求对象,,post发送的参数list,指定格式 post.setEntity(new UrlEncodedFormEntity(list,"utf-8")); if (headerMap != null) {for (String str : headerMap.keySet()) {post.addHeader(str, headerMap.get(str)); }}CloseableHttpClient client = HttpClients.createDefault(); //启动执行请求,并获得返回值 CloseableHttpResponse response = client.execute(post); //得到返回的entity对象 HttpEntity entity = response.getEntity(); //把实体对象转换为string String result = EntityUtils.toString(entity, "utf-8"); //为防止频繁调用一个接口导致接口爆掉,每次调用完成后停留100毫秒 Thread.sleep(100); //返回内容 return result; } catch (Exception e1) {e1.printStackTrace(); return ""; }}}
天气接口参考地址:
WeatherWebService Web 服务 (webxml.com.cn)
免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://itzsg.com/32536.html