这篇文章主要描述如何通过程序来访问网页内容,这是访问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. 直接修改.NET程序集 LLBL Gen 2.x-4.x 许可授权方法研究

    做数据库开发,如果要用ORM,LLBL Gen是一款优秀的框架和工具,目前最新版本是4.0.同时也推出了Lite免费版本,与Visual Studio的Express版本一样, 免费,但是它仅仅只支持 ...

  2. JSP网站开发基础总结《八》

    JSP的学习总结到本篇已经八篇了,内容比较多,但都是实战,本篇最后为大家介绍一个小效果:百度分页.就是当我们遍历的数据对象较多时,这时我们就会看到了这个效果了,那他是如何实现的呢?下面我们就一起学习一 ...

  3. Angular从0到1:function(下)

    1.前言 2.function(下) 2.13.angular.isArray(★★) angular.isArray用于判断对象是不是数组,等价于Array.isArray console.log( ...

  4. C#预处理器指令 ,你造吗??? (●'◡'●)

    什么是c#预处理指令?? 用于在 C# 源代码中嵌入的编译器命令. C#预处理器指令有哪些?? ↓↓↓这些就是预处理器指令啦 下面我们一一道来(●'◡'●) 1.#if ,#elif,#else,en ...

  5. 转载--tomcat整合apr

    原文地址: http://zhaosheng.wolf.blog.163.com/blog/static/115304589201212845341723/ APR(Apache Portable R ...

  6. Nutch源码阅读进程1---inject

    最近在Ubuntu下配置好了nutch和solr的环境,也用nutch爬取了一些网页,通过solr界面呈现,也过了一把自己建立小搜索引擎的瘾,现在该静下心来好好看看nutch的源码了,先从Inject ...

  7. Linux C++ 调试神技--如何将Linux C++ 可执行文件逆向工程到Intel格式汇编

    Linux C++ 调试神技--如何将Linux C++ 可执行文件逆向工程到Intel格式汇编 对于许多在windows 上调试代码的人而言, Intel IA32格式的汇编代码可能并不陌生,因为种 ...

  8. JavaScript中以一个方法作为参数的写法

    前言,我们写js的时候,经常会看到一些方法,比如说: $("#ids").click(function( alert("Click me"); )); ---- ...

  9. Android聚合广告AFP的对接系统设计

    工作需要,要对接阿里妈妈的广告聚合平台,简称AFP.对于一般的应用而言,想要流量变现,广告是显而易见的手段,尤其是在中国,打开一个千万级别的用户,肯定有某个地方是有对接广告的,只不过明不明显而已. 阿 ...

  10. 第24/24周 数据库维护(Database Maintenance)

    哇哦,光阴似箭!欢迎回到性能调优培训的最后一期.今天我会详细讲下SQL Server里的数据库维护,尤其是索引维护操作,还有如何进行数据库维护. 索引维护 作为一个DBA,数据库维护是你工作中非常重要 ...