这篇文章主要描述如何通过程序来访问网页内容,这是访问REST服务的基础。

  在Java中,我们可以使用HttpUrlConnection类来实现,代码如下。

 package http.base;

 import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.Map;
import java.util.Vector; public class HttpRequester {
private String defaultContentEncoding; public HttpRequester() {
this.defaultContentEncoding = Charset.defaultCharset().name();
} public HttpResponse sendGet(String urlString) throws IOException {
return this.send(urlString, "GET", null, null);
} public HttpResponse sendGet(String urlString, Map<String, String> params)
throws IOException {
return this.send(urlString, "GET", params, null);
} public HttpResponse sendGet(String urlString, Map<String, String> params,
Map<String, String> propertys) throws IOException {
return this.send(urlString, "GET", params, propertys);
} public HttpResponse sendPost(String urlString) throws IOException {
return this.send(urlString, "POST", null, null);
} public HttpResponse sendPost(String urlString, Map<String, String> params)
throws IOException {
return this.send(urlString, "POST", params, null);
} public HttpResponse sendPost(String urlString, Map<String, String> params,
Map<String, String> propertys) throws IOException {
return this.send(urlString, "POST", params, propertys);
} private HttpResponse send(String urlString, String method,
Map<String, String> parameters, Map<String, String> propertys)
throws IOException {
HttpURLConnection urlConnection = null; if (method.equalsIgnoreCase("GET") && parameters != null) {
StringBuffer param = new StringBuffer();
int i = 0;
for (String key : parameters.keySet()) {
if (i == 0)
param.append("?");
else
param.append("&");
param.append(key).append("=").append(parameters.get(key));
i++;
}
urlString += param;
}
URL url = new URL(urlString);
urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod(method);
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.setUseCaches(false); if (propertys != null)
for (String key : propertys.keySet()) {
urlConnection.addRequestProperty(key, propertys.get(key));
} if (method.equalsIgnoreCase("POST") && parameters != null) {
StringBuffer param = new StringBuffer();
for (String key : parameters.keySet()) {
param.append("&");
param.append(key).append("=").append(parameters.get(key));
}
urlConnection.getOutputStream().write(param.toString().getBytes());
urlConnection.getOutputStream().flush();
urlConnection.getOutputStream().close();
} return this.makeContent(urlString, urlConnection);
} private HttpResponse makeContent(String urlString,
HttpURLConnection urlConnection) throws IOException {
HttpResponse httpResponser = new HttpResponse();
try {
InputStream in = urlConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(in));
httpResponser.contentCollection = new Vector<String>();
StringBuffer temp = new StringBuffer();
String line = bufferedReader.readLine();
while (line != null) {
httpResponser.contentCollection.add(line);
temp.append(line).append("/r/n");
line = bufferedReader.readLine();
}
bufferedReader.close(); String ecod = urlConnection.getContentEncoding();
if (ecod == null)
ecod = this.defaultContentEncoding; httpResponser.urlString = urlString; httpResponser.defaultPort = urlConnection.getURL().getDefaultPort();
httpResponser.file = urlConnection.getURL().getFile();
httpResponser.host = urlConnection.getURL().getHost();
httpResponser.path = urlConnection.getURL().getPath();
httpResponser.port = urlConnection.getURL().getPort();
httpResponser.protocol = urlConnection.getURL().getProtocol();
httpResponser.query = urlConnection.getURL().getQuery();
httpResponser.ref = urlConnection.getURL().getRef();
httpResponser.userInfo = urlConnection.getURL().getUserInfo(); httpResponser.content = new String(temp.toString().getBytes(), ecod);
httpResponser.contentEncoding = ecod;
httpResponser.code = urlConnection.getResponseCode();
httpResponser.message = urlConnection.getResponseMessage();
httpResponser.contentType = urlConnection.getContentType();
httpResponser.method = urlConnection.getRequestMethod();
httpResponser.connectTimeout = urlConnection.getConnectTimeout();
httpResponser.readTimeout = urlConnection.getReadTimeout(); return httpResponser;
} catch (IOException e) {
throw e;
} finally {
if (urlConnection != null)
urlConnection.disconnect();
}
} public String getDefaultContentEncoding() {
return this.defaultContentEncoding;
} public void setDefaultContentEncoding(String defaultContentEncoding) {
this.defaultContentEncoding = defaultContentEncoding;
}
}

HttpRequest类

 package http.base;

 import java.util.Vector;

 public class HttpResponse {

     String urlString;
int defaultPort;
String file;
String host;
String path;
int port;
String protocol;
String query;
String ref;
String userInfo;
String contentEncoding;
String content;
String contentType;
int code;
String message;
String method;
int connectTimeout;
int readTimeout;
Vector<String> contentCollection; public String getContent() {
return content;
} public String getContentType() {
return contentType;
} public int getCode() {
return code;
} public String getMessage() {
return message;
} public Vector<String> getContentCollection() {
return contentCollection;
} public String getContentEncoding() {
return contentEncoding;
} public String getMethod() {
return method;
} public int getConnectTimeout() {
return connectTimeout;
} public int getReadTimeout() {
return readTimeout;
} public String getUrlString() {
return urlString;
} public int getDefaultPort() {
return defaultPort;
} public String getFile() {
return file;
} public String getHost() {
return host;
} public String getPath() {
return path;
} public int getPort() {
return port;
} public String getProtocol() {
return protocol;
} public String getQuery() {
return query;
} public String getRef() {
return ref;
} public String getUserInfo() {
return userInfo;
} }

HttpResponse类

  下面是一个简单的测试类。

 package http.base;

 public class HttpTest {
public static void main(String[] args) {
try {
HttpRequester request = new HttpRequester();
HttpResponse hr = request.sendGet("http://www.baidu.com"); System.out.println(hr.getUrlString());
System.out.println(hr.getProtocol());
System.out.println(hr.getHost());
System.out.println(hr.getPort());
System.out.println(hr.getContentEncoding());
System.out.println(hr.getMethod()); System.out.println(hr.getContent()); } catch (Exception e) {
e.printStackTrace();
}
}
}

  因为REST服务的返回值一般都是JSON对象,下一篇文章中,我们来看Java对象和JSON之间如何转换。

如何在BPM中使用REST服务(1):通过程序访问网页内容的更多相关文章

  1. 如何在springMVC 中对REST服务使用mockmvc 做测试

    如何在springMVC 中对REST服务使用mockmvc 做测试 博客分类: java 基础 springMVCmockMVC单元测试  spring 集成测试中对mock 的集成实在是太棒了!但 ...

  2. 如何在ubuntu中启用SSH服务

    如何在ubuntu14.04 中启用SSH服务 开篇科普:  SSH 为 Secure Shell 的缩写,由 IETF 的网络工作小组(Network Working Group)所制定:SSH 为 ...

  3. 如何在Ruby中编写微服务?

    [编者按]本文作者为 Pierpaolo Frasa,文章通过详细的案例,介绍了在Ruby中编写微服务时所需注意的方方面面.系国内 ITOM 管理平台 OneAPM 编译呈现. 最近,大家都认为应当采 ...

  4. 如何在IIS中设置HTTPS服务

    文章:https://support.microsoft.com/en-us/help/324069/how-to-set-up-an-https-service-in-iis 在这个任务中 摘要 为 ...

  5. 如何在 IIS 中设置 HTTPS 服务

    Windows Server2008.IIS7启用CA认证及证书制作完整过程 这篇文章介绍了如何安装证书申请工具: 如何在iis创建证书申请: 如何使用iis申请证书生成的txt文件,在工具中开始申请 ...

  6. 技术干货丨如何在VIPKID中构建MQ服务

    小结: 1. https://mp.weixin.qq.com/s/FQ-DKvQZSP061kqG_qeRjA 文 |李伟 VIPKID数据中间件架构师 交流微信 | datapipeline201 ...

  7. 如何在Linux中关闭apache服务(转)

    ??? 最近在写一个简单的http服务器,调试的时候发现apache服务器也在机器上跑着,所以得先把apache关掉.当时装apache的时候就是用了普通的sudo get,也不知道装到哪儿了.到网上 ...

  8. 如何在php中优雅的地调用python程序

    1.准备工作   安装有python和php环境的电脑一台. 2.书写程序. php程序如下 我们也可以将exec('python test.py') 换成 system('python test.p ...

  9. 如何在Android中的Activity启动第三方应用程序?

    如何在点击某个按键后,执行启动第三方应用程序界面? /** * <功能描述> 启动应用程序 * * @return void [返回类型说明] */ private void startU ...

随机推荐

  1. 安卓学习进程(2)Android开发环境的搭建

        本节将分为五个步骤来完成Android开发环境的部署. 第一步:安装JDK. 第二步:配置Windows上JDK的变量环境 . 第三步:下载安装Eclipse . 第四步:下载安装Androi ...

  2. JavaScript闭包(一)——实现

    闭包的官方的解释是:一个拥有许多变量和绑定了这些变量的环境的表达式(通常是一个函数),因而这些变量也是该表达式的一部分. 通俗点的说法是: 从理论角度:所有的函数.因为它们都在创建的时候就将上层上下文 ...

  3. 响应式网页中,如何只用CSS实现div的高和宽保持固定比例

    引言: 如果div里是<img>,原生就支持. .item img {     float: left;     margin:5%;     width: 20%; } >> ...

  4. HTML5本地存储 Web Storage

    Web Storage基本介绍 HTML5 定义了本地存储规范 Web Storage , 提供了两种存储类型 API  sessionStorage 和 localStorage,二者的差异主要是数 ...

  5. java类加载器-Tomcat类加载器

    在上文中,已经介绍了系统类加载器以及类加载器的相关机制,还自定制类加载器的方式.接下来就以tomcat6为例看看tomat是如何使用自定制类加载器的.(本介绍是基于tomcat6.0.41,不同版本可 ...

  6. Redis发布订阅实现原理

    发布订阅中使用到的命令就只有三个:PUBLISH,SUBSCRIBE,PSUBSCRIBE PUBLISH 用于发布消息 SUBSCRIBE 也叫频道订阅,用于订阅某一特定的频道 PSUBSCRIBE ...

  7. window、document、html、body、element的事件属性比较

    在分析jQuery的事件的时候有提到绑定事件的方式: Dean Edwards的跨浏览器事件绑定使用的方式是 element["on" + type] = handleEvent; ...

  8. 分享我基于NPOI+ExcelReport实现的导入与导出EXCEL类库:ExcelUtility

    1. ExcelUtility功能:  1.将数据导出到EXCEL(支持XLS,XLSX,支持多种类型模板,支持列宽自适应)  类名:ExcelUtility. Export  2.将EXCEL ...

  9. Moon.Orm 5.0(MQL版)及之前版本的开源计划

    开源综述:步步开源 Moon.Orm 5.0 (MQL版) 版本维护及下载 (跟踪发布) Moon.Orm 5.0系列文章 Moon.Orm 5.0性能问题,将发言权交给你! 一.5.0目前的情况,步 ...

  10. IHTMLDocument2

    {IHTMLDocument2 方法:} write //写入 writeln //写入并换行 open //打开一个流,以收集 document.write 或 document.writeln 的 ...