这篇文章主要描述如何通过程序来访问网页内容,这是访问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. Mybatis中SqlMapper配置的扩展与应用(2)

    三.子表删除兼容问题 这个问题,使用SQL配置函数不太好处理,而且就算使用SQL配置函数,也不够直观,有点自动生成SQL的意味,太Hibernate了(不过要是可以兼收Hibernate和Mybati ...

  2. Socket实现仿QQ聊天(可部署于广域网)附源码(2)-服务器搭建

    1.前言 这是本系列的第二篇文章,第一篇文章得到了很多朋友们的支持,在这里表示非常的感谢.对于这一系列文章需要补充的是这只是一篇入门级别的Socket通信文章,对于专业人员来说完全可以跳过.本文只介绍 ...

  3. Orlion个人博客 | 全栈工程师之路-www.orlion.ga

    自己用wordpress+bootstrap搭建了一个博客,网址http://www.orlion.ga,用来记录博主学习和成长,主要关注JAVA.LANMP.前端与客户端(Android).算法与数 ...

  4. CSDN 论坛招聘区是不是有潜规则?在Cnblog招个人试试...

    CSDN 论坛招聘区是不是有潜规则? 在招聘区发了两个招聘贴都被删掉了... 而且没有任何提示和原因,或者站内短信提示.... 虽然csdn现在很水...不过在那边之前待了几年还是有点感情的 想顺便内 ...

  5. [c++] Pieces of knowledge

    再系统地学一遍c++,查缺补漏. wchar_t L'a' stored in wchar_t. size of types cout << numeric_limits<doubl ...

  6. 百度地图JavaScript API覆盖物旋转时出现偏移

    在项目中,调用百度地图JavaScript API,做覆盖物的旋转再添加到地图上,结果出现偏移了. 调试过程中的效果图: 发现图片的旋转并不是按车子的中心来的,而是之外的一个点.最后发现犯了一个很细节 ...

  7. PHP面向对象中的重要知识点(二)

    1. __toString: 当对象被打印时,如果该类定义了该方法,则打印该方法的返回值,否则将按照PHP的缺省行为输出打印结果.该方法类似于Java中的toString(). <?php cl ...

  8. Windows Azure Virtual Machine (33) Azure虚拟机删除重建

    <Windows Azure Platform 系列文章目录> 注意:本文介绍的重建Azure虚拟机,必须在同一个订阅内删除重建,必须在同一个订阅内删除重建,必须在同一个订阅内删除重建. ...

  9. c# 指定的存储区提供程序在配置中找不到,或者无效

    <system.data> <DbProviderFactories> <remove invariant="System.Data.SQLite"/ ...

  10. HtmlAgilityPack 删除script、style以及注释标签

    foreach(var script in doc.DocumentNode.Descendants("script").ToArray()) script.Remove(); f ...