java web api接口调用
Web Services 被W3C进行了标准化定义。
Web Services 发布到网上,可以公布到某个全局注册表,自动提供服务URL,服务描述、接口调用要求、参数说明以及返回值说明。比如中国气象局可以发布天气预报服务。所有其它网站或手机App如果需要集成天气预报功能,都可以访问该Web Service获取数据。
Web Services 主要设计目标是提供公共服务。
Web Services 全部基于XML。按照W3C标准来描述服务的各个方面(参数、参数传递、返回值及服务发布发现等)。要描述清楚Web Services标准的各个方面,可能需要2000页的文档。
Web Services 还有标准的身份验证方式(非公共服务时验证使用者身份)。
轻量化的Web API
公司内部使用的私有服务,我们知道它的接口Url,因此不需要自动发现它。我们有它的服务接口文档,因此也不需要自动描述和自动调用。
即使Web Services的特性(自动发现、自动学会调用方式)很美好,但私有服务往往不需要这些。
Web API一般基于HTTP/REST来实现,什么都不需要定义,参数(输入的数据)可以是JSON, XML或者简单文本,响应(输出数据)一般是JSON或XML。它不提供服务调用标准和服务发现标准。可以按你服务的特点来写一些简单的使用说明给使用者。
获取远程数据的方式正在从Web Services向Web API转变。
Web Services的架构要比Web API臃肿得多,它的每个请求都需要封装成XML并在服务端解封。因此它不易开发且吃更多的资源(内存、带宽)。性能也不如Web API。
/**
* 根据指定url,编码获得字符串
*
* @param address
* @param Charset
* @return
*/
public static String getStringByConAndCharset(String address, String Charset) {
StringBuffer sb;
try {
URL url = new URL(address);
URLConnection con = url.openConnection();
BufferedReader bw = new BufferedReader(new InputStreamReader(con.getInputStream(), Charset));
String line;
sb = new StringBuffer();
while ((line = bw.readLine()) != null) {
sb.append(line + "\n");
}
bw.close();
} catch (Exception e) {
e.printStackTrace();
sb = new StringBuffer();
}
return sb.toString();
}
/**
* 通过post方式获取页面源码
*
* @param urlString
* url地址
* @param paramContent
* 需要post的参数
* @param chartSet
* 字符编码(默认为ISO-8859-1)
* @return
* @throws IOException
*/
public static String postUrl(String urlString, String paramContent, String chartSet, String contentType) {
long beginTime = System.currentTimeMillis();
if (chartSet == null || "".equals(chartSet)) {
chartSet = "ISO-8859-1";
}
StringBuffer result = new StringBuffer();
BufferedReader in = null;
try {
URL url = new URL((urlString));
URLConnection con = url.openConnection();
// 设置链接超时
con.setConnectTimeout(3000);
// 设置读取超时
con.setReadTimeout(3000);
// 设置参数
con.setDoOutput(true);
if (contentType != null && !"".equals(contentType)) {
con.setRequestProperty("Content-type", contentType);
}
OutputStreamWriter writer = new OutputStreamWriter(con.getOutputStream(), chartSet);
writer.write(paramContent);
writer.flush();
writer.close();
in = new BufferedReader(new InputStreamReader(con.getInputStream(), chartSet));
String line = null;
while ((line = in.readLine()) != null) {
result.append(line + "\r\n");
}
in.close();
} catch (MalformedURLException e) {
logger.error("Unable to connect to URL: " + urlString, e);
} catch (SocketTimeoutException e) {
logger.error("Timeout Exception when connecting to URL: " + urlString, e);
} catch (IOException e) {
logger.error("IOException when connecting to URL: " + urlString, e);
} finally {
if (in != null) {
try {
in.close();
} catch (Exception ex) {
logger.error("Exception throws at finally close reader when connecting to URL: " + urlString, ex);
}
}
long endTime = System.currentTimeMillis();
logger.info("post用时:" + (endTime - beginTime) + "ms");
}
return result.toString();
}
/**
* 发送https请求
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr 提交的数据
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
* @throws NoSuchProviderException
* @throws NoSuchAlgorithmException
*/
public static JSONObject httpsRequest(String requestUrl, String requestMethod, String outputStr) throws Exception {
JSONObject json = null;
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setSSLSocketFactory(ssf);
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setUseCaches(false);
// 设置请求方式(GET/POST)
conn.setRequestMethod(requestMethod);
// 当outputStr不为null时向输出流写数据
if (null != outputStr) {
OutputStream outputStream = conn.getOutputStream();
// 注意编码格式
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 从输入流读取返回内容
InputStream inputStream = conn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
StringBuffer buffer = new StringBuffer();
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
// 释放资源
bufferedReader.close();
inputStreamReader.close();
inputStream.close();
inputStream = null;
conn.disconnect();
json = JSON.parseObject(buffer.toString());
String errcode = json.getString("errcode");
if (!StringUtil.isBlank(errcode) && !errcode.equals("0")) {
logger.error(json.toString());
throw new SysException("ERRCODE:"+ errcode);
}
return json;
}
}
java web api接口调用的更多相关文章
- WebApi系列~通过HttpClient来调用Web Api接口~续~实体参数的传递
回到目录 上一讲中介绍了使用HttpClient如何去调用一个标准的Web Api接口,并且我们知道了Post,Put方法只能有一个FromBody参数,再有多个参数时,上讲提到,需要将它封装成一个对 ...
- Http下的各种操作类.WebApi系列~通过HttpClient来调用Web Api接口
1.WebApi系列~通过HttpClient来调用Web Api接口 http://www.cnblogs.com/lori/p/4045413.html HttpClient使用详解(java版本 ...
- ASP.NET Web API 接口执行时间监控
软件产品常常会出现这样的情况:产品性能因某些无法预料的瓶颈而受到干扰,导致程序的处理效率降低,性能得不到充分的发挥.如何快速有效地找到软件产品的性能瓶颈,则是我们感兴趣的内容之一. 在本文中,我将解释 ...
- Web API接口之FileReader
Web API接口之FileReader *:first-child { margin-top: 0 !important; } body>*:last-child { margin-botto ...
- Winform混合式开发框架访问Web API接口的处理
在我的混合式开发框架里面,集成了WebAPI的访问,这种访问方式不仅可以实现简便的数据交换,而且可以在多种平台上进行接入,如Winform程序.Web网站.移动端APP等多种接入方式,Web API的 ...
- Web API接口设计经验总结
在Web API接口的开发过程中,我们可能会碰到各种各样的问题,我在前面两篇随笔<Web API应用架构在Winform混合框架中的应用(1)>.<Web API应用架构在Winfo ...
- 如何让你的 Asp.Net Web Api 接口,拥抱支持跨域访问。
由于 web api 项目通常是被做成了一个独立站点,来提供数据,在做web api 项目的时候,不免前端会遇到跨域访问接口的问题. 刚开始没做任何处理,用jsonp的方式调用 web api 接口, ...
- Web API接口 安全验证
在上篇随笔<Web API应用架构设计分析(1)>,我对Web API的各种应用架构进行了概括性的分析和设计,Web API 是一种应用接口框架,它能够构建HTTP服务以支撑更广泛的客户端 ...
- Asp.Net Web Api 接口,拥抱支持跨域访问。
如何让你的 Asp.Net Web Api 接口,拥抱支持跨域访问. 由于 web api 项目通常是被做成了一个独立站点,来提供数据,在做web api 项目的时候,不免前端会遇到跨域访问接口的问题 ...
随机推荐
- [Oracle入门级]知识概况
oracle各个版本间的主要技术更新 oracle 增加数据库创建和存储对象 oracle 8i 整体性能提升 oracle9i 实施应用集群 oracle 10g 支持网格计算 oracle 11g ...
- Python学习过程(二)
条件判断和循环 条件判断 age = 20 if age >= 18: print 'your age is',age print 'adult' elif age >=6 : print ...
- P4199 万径人踪灭 FFT + manacher
\(\color{#0066ff}{ 题目描述 }\) \(\color{#0066ff}{输入格式}\) 一行,一个只包含a,b两种字符的字符串 \(\color{#0066ff}{输出格式}\) ...
- shared_ptr 和auto_ptr智能指针
shared_ptr:计数的智能指针 它是一个包装了new操作符在堆上分配的动态对象,但它实现的是引用计数型的智能指针 ,可以被自由地拷贝和赋值,在任意的地方共享它,当没有代码使用(引用计数为0)它时 ...
- Qt 学习之路 2(26):反走样
Qt 学习之路 2(26):反走样 豆子 2012年11月12日 Qt 学习之路 2 9条评论 我们在光栅图形显示器上绘制非水平.非垂直的直线或多边形边界时,或多或少会呈现锯齿状外观.这是因为直线和多 ...
- FPGA实战操作(1) -- SDRAM(操作说明)
SDRAM是做嵌入式系统中,常用是的缓存数据的器件.基本概念如下(注意区分几个主要常见存储器之间的差异): SDRAM(Synchronous Dynamic Random Access Memory ...
- Mybatis学习笔记(五) —— Mapper.xml(输入映射和输出映射)
一.parameterType(输入类型) 1.1 传递简单类型 <!-- 根据用户id查询用户 --> <select id="queryUserById" p ...
- about rand and reflect
select regexp_replace(reflect("java.util.UUID", "randomUUID"), "-", &q ...
- testlink数据库访问密码修改
testlink重启后数据库连接不上将会报错 错误:1045 - Access denied for user 'my_db '@'localhost' (using password: YES) 怎 ...
- 基于Visual Studio .NET2015的单元测试 OpenCover
https://www.cnblogs.com/XiaoRuLiang/p/10095723.html 基于Visual Studio .NET2015的单元测试 1. 在Visual Stud ...