利用URLConnection http协议实现webservice接口功能(附HttpUtil.java)
URL的openConnection()方法将返回一个URLConnection对象,该对象表示应用程序和 URL 之间的通信链接。程序可以通过URLConnection实例向该URL发送请求、读取URL引用的资源。
验证身份证号码与姓名是否一致的接口:
http://132.228.156.103:9188/DataSync/CheckResult?SeqNo=1&ChannelID=1003&ID=41272xxxxx&Name=xxx

需求:
在用户填入身份证号时校验其准确性。
页面:
var id_number = $("#idNumber").val();
var user_name = $("#staffName").val();
$.ajax({
type:'POST',
url:contextPath + "/check/checkIdNumber.do",
data:{
id_number:id_number,
user_name:user_name
},
dataType:'json',
success:function(json){
if(json.result != "00"){
$.messager.alert('警告','姓名与身份证号码不一致,请核对!');
}else{
$.ajax({
type : 'POST',
url : contextPath + "/Staff/modifyIdNumber.do",
data : {
ID_NUMBER:id_number,
mobileNumber:$("#mobileNumber").val()
},
dataType : 'json',
success : function(json) {
if (json.status) {
msgShow('系统提示', '实名认证成功', 'info');
isSimplePwd = true;
$('#idNumberWindow').window('close');
}else{
msgShow('系统提示', json.info, 'warning');
}
}
});
}
}
});
控制层:
/**
* 验证身份证号码与姓名是否一致
* @param request
* @param response
* @throws IOException
*/
@RequestMapping("/checkIdNumber.do")
@ResponseBody
public void checkIdNumber(HttpServletRequest request, HttpServletResponse response) throws IOException{
String id_number = request.getParameter("id_number");
String user_name = request.getParameter("user_name");
Map<String, String> param = new HashMap<String, String>();
param.put("ID", id_number);
param.put("Name", user_name);
param.put("SeqNo", "1");//流水号
param.put("ChannelID", "1003");//渠道号
String result = HttpUtil.sendPost(Constants.DATA_SYNC, param, "utf-8");
JSONObject resObj = JSONObject.fromObject(result);
Map<String, Object> rs = new HashMap<String, Object>();
rs.put("result", resObj.get("result").toString());
rs.put("smsg", resObj.get("smsg").toString());
write(response, rs);
}
数据返回页面的另一种方式:(尤其是当返回结果是List集合时,不能使用write(response,rs))
BaseServletTool.sendParam(response, rs.toString());
服务层:
/**
* POST请求,Map形式数据
* @param url 请求地址
* @param param 请求数据
* @param charset 编码方式
*/
public static String sendPost(String url, Map<String, String> param, String charset) { StringBuffer buffer = new StringBuffer();
if (param != null && !param.isEmpty()) {
for (Map.Entry<String, String> entry : param.entrySet()) {
buffer.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue())).append("&");
}
}
buffer.deleteCharAt(buffer.length() - 1); PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
//设置鉴权属性
//connection.setRequestProperty("X-Authorization", " Bearer " + String.valueOf(param.get("token")));
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(buffer);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
} /**
* TODO GET请求,字符串形式数据
* @param url 请求地址
* @param charset 编码方式
*
*/
public String sendGet(String url, Map<String, String> param, String charset) {
String result = "";
BufferedReader in = null;
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
//设置鉴权属性
connection.setRequestProperty("X-Authorization", " Bearer " + String.valueOf(param.get("token")));
// 建立实际的连接
connection.connect();
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), charset));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
根据不同的请求方式选择sendPost()或sendGet()方法,如果需要鉴权,添加:
connection.setRequestProperty("X-Authorization", " Bearer " + String.valueOf(param.get("token")));
附HttpUtil.java
package com.system.tool; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry; /**
* 向指定服务器(外网)发送GET或POST请求工具类
* @author wangxiangyu
*
*/
public class HttpUtil { private static int connectTimeOut = 5000;
private static int readTimeOut = 10000;
private static String requestEncoding = "UTF-8"; /**
* GET请求,字符串形式数据
* @param url 请求地址
* @param charset 编码方式
*
*/
public static String sendGet(String url, String charset) {
String result = "";
BufferedReader in = null;
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection connection = realUrl.openConnection();
// 设置通用的请求属性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
//设置鉴权属性
//connection.setRequestProperty("X-Authorization", " Bearer " + String.valueOf(param.get("token")));
// 建立实际的连接
connection.connect();
// 定义 BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(connection.getInputStream(), charset));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送GET请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
} /**
* POST请求,字符串形式数据
* @param url 请求地址
* @param param 请求数据
* @param charset 编码方式
*
*/
public static String sendPostUrl(String url, String param, String charset) { PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(param);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
/**
* POST请求,Map形式数据
* @param url 请求地址
* @param param 请求数据
* @param charset 编码方式
*/
public static String sendPost(String url, Map<String, String> param, String charset) { StringBuffer buffer = new StringBuffer();
if (param != null && !param.isEmpty()) {
for (Map.Entry<String, String> entry : param.entrySet()) {
buffer.append(entry.getKey()).append("=").append(URLEncoder.encode(entry.getValue())).append("&");
}
}
buffer.deleteCharAt(buffer.length() - 1); PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(buffer);
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
String line;
while ((line = in.readLine()) != null) {
result += line;
} } catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
} /**
* POST请求,字符串形式数据
* @param url 请求地址
* @param param 请求数据
*/
public static String sendPost(String url, Map<String,Object> param) { PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打开和URL之间的连接
URLConnection conn = realUrl.openConnection();
// 设置通用的请求属性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("Content-Type", "application/form-data");
conn.setRequestProperty("Content-Length", String.valueOf(JsonUtil.simpleMapToJsonStr(param).length()));
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 发送POST请求必须设置如下两行
conn.setDoOutput(true);
conn.setDoInput(true);
// 获取URLConnection对象对应的输出流
out = new PrintWriter(conn.getOutputStream());
// 发送请求参数
out.print(JsonUtil.simpleMapToJsonStr(param));
// flush输出流的缓冲
out.flush();
// 定义BufferedReader输入流来读取URL的响应
in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
System.out.println("url>>>>>>>>:"+url);
System.out.println("param>>>>>>>>:"+JsonUtil.simpleMapToJsonStr(param));
System.out.println("result>>>>>>>>:"+result);
} catch (Exception e) {
System.out.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
// 使用finally块来关闭输出流、输入流
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
} public static String doPost(String reqUrl, Map<String, String> parameters, String recvEncoding) {
HttpURLConnection url_con = null;
String responseContent = null;
String vchartset = recvEncoding == "" ? HttpUtil.requestEncoding : recvEncoding;
try {
StringBuffer params = new StringBuffer();
for (Iterator<?> iter = parameters.entrySet().iterator(); iter.hasNext();) {
Entry<?, ?> element = (Entry<?, ?>) iter.next();
params.append(element.getKey().toString());
params.append("=");
params.append(URLEncoder.encode(element.getValue().toString(), vchartset));
params.append("&");
} if (params.length() > 0) {
params = params.deleteCharAt(params.length() - 1);
} URL url = new URL(reqUrl);
url_con = (HttpURLConnection) url.openConnection();
url_con.setRequestMethod("POST");
url_con.setConnectTimeout(HttpUtil.connectTimeOut);
url_con.setReadTimeout(HttpUtil.readTimeOut);
url_con.setDoOutput(true);
byte[] b = params.toString().getBytes();
url_con.getOutputStream().write(b, 0, b.length);
url_con.getOutputStream().flush();
url_con.getOutputStream().close(); InputStream in = url_con.getInputStream();
byte[] echo = new byte[10 * 1024];
int len = in.read(echo);
responseContent = (new String(echo, 0, len)).trim();
int code = url_con.getResponseCode();
if (code != 200) {
responseContent = "ERROR" + code;
} } catch (IOException e) {
System.out.println("网络故障:" + e.toString());
} finally {
if (url_con != null) {
url_con.disconnect();
}
}
return responseContent;
} public static String http(String url, Map<String, Object> params) {
URL u = null;
HttpURLConnection con = null;
// 构建请求参数
StringBuffer sb = new StringBuffer();
if (params != null) {
for (Entry<String, Object> e : params.entrySet()) {
sb.append(e.getKey());
sb.append("=");
sb.append(e.getValue());
sb.append("&");
}
sb.substring(0, sb.length() - 1);
}
System.out.println("send_url:" + url);
System.out.println("send_data:" + sb.toString());
// 尝试发送请求
try {
u = new URL(url);
con = (HttpURLConnection) u.openConnection();
//// POST 只能为大写,严格限制,post会不识别
con.setRequestMethod("POST");
con.setDoOutput(true);
con.setDoInput(true);
con.setUseCaches(false);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
OutputStreamWriter osw = new OutputStreamWriter(con.getOutputStream(), "UTF-8");
osw.write(JsonUtil.simpleMapToJsonStr(params));
osw.flush();
osw.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (con != null) {
con.disconnect();
}
} // 读取返回内容
StringBuffer buffer = new StringBuffer();
try {
//一定要有返回值,否则无法把请求发送给server端。
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream(), "UTF-8"));
String temp;
while ((temp = br.readLine()) != null) {
buffer.append(temp);
buffer.append("\n");
}
} catch (Exception e) {
e.printStackTrace();
} return buffer.toString();
} }
利用URLConnection http协议实现webservice接口功能(附HttpUtil.java)的更多相关文章
- spring集成cxf实现webservice接口功能
由于cxf的web项目已经集成了Spring,所以cxf的服务类都是在spring的配置文件中完成的.以下是步骤:第一步:建立一个web项目.第二步:准备所有jar包.将cxf_home\lib项目下 ...
- 利用MyEclipse开发一个调用webservice接口的程序
上一篇文章我们已经学习了如何使用Java 工具MyEclipse开发一个webservice接口,那么接口开发好了如何调用?接下来我们就来解决这个问题. 1:首先随便创建一个Java project选 ...
- Https Webservice接口的免证书调用
目录 前言 思路 方案 Axis调用 HttpClient调用 参考链接 前言 在调用https协议的Webservice接口时,如果没有做证书验证,一般会报javax.net.ssl.SSLHand ...
- Python的Web编程[2] -> WebService技术[0] -> 利用 Python 调用 WebService 接口
WebService技术 / WebService Technology 1 关于webservice / Constants WebService是一种跨编程语言和跨操作系统平台的远程调用技术. W ...
- 【JMeter4.0学习(三)】之SoapUI创建WebService接口模拟服务端以及JMeter对SOAP协议性能测试脚本开发
目录: 创建WebService接口模拟服务端 下载SoapUI 新建MathUtil.wsdl文件 创建一个SOAP项目 接口模拟服务端配置以及启动 JMeter对SOAP协议性能测试脚本开发 [阐 ...
- Java调用WebService接口实现发送手机短信验证码功能,java 手机验证码,WebService接口调用
近来由于项目需要,需要用到手机短信验证码的功能,其中最主要的是用到了第三方提供的短信平台接口WebService客户端接口,下面我把我在项目中用到的记录一下,以便给大家提供个思路,由于本人的文采有限, ...
- lr使用soap协议,来对webservice接口进行测试
实际项目中基于WSDL来测试WebService的情况并不多,WSDL并不是WebService测试的最佳选择. 最主要的原因还是因为WSDL文档过于复杂. 在案例(天气预报WebService服务) ...
- 通过iTop Webservice接口丰富OQL的功能
通过Python调用iTop的Webservice接口: #!/usr/bin/env python #coding: utf-8 import requests import json itopur ...
- 从xfire谈WebService接口化编程
前段时间有博友在看我的博文<WebService入门案例>后,发邮件问我关于WebService 接口在java中的开发,以及在实际生产环境中的应用.想想自己入职也有一段时间了,似乎也该总 ...
随机推荐
- python 内置函数,匿名函数,sorted,filter,map,递归,二分法,冒泡算法 eval
############################总结#################################1. lambda 匿名函数 语法——lambda 参数:返回值 __na ...
- HDU 1045(炮台安置 DFS)
题意是在 n*n 的方格中进行炮台的安置,炮台不能处于同一行或同一列(类似于八皇后问题),但若是炮台间有墙壁阻挡,则可以同时安置这对炮台.问图中可以安放的最大炮台数目. 用深搜的方法,若此处为空地,则 ...
- 解决 git push Failed to connect to 127.0.0.1 port 8-87: 拒绝连接
今天在本地使用nsq 测试的时候总是提示端口被占用 通过查看环境变量确实存在该代理 如何解决 使用netstat 命令查看端口被占用情况 根据经常ID号查看是哪一个进程正在被占用 如何还是不行,则在[ ...
- pycharm仿sublime配色
1.设置IDE皮肤主题 file->setting->appearance->theme->darcula 2.setting中搜索python,将主题设置成Monokai,然 ...
- Silverlight 样式的灵活使用
众所周知,Silverlight将界面设计与代码实现分开.即便如此,如果不能灵活地运用样式Style,开发的效率依然会比较低.比如,针对类似的TextBlock,你可能需要反复地在设计器xaml中复制 ...
- FormatMessage
FormatMessage 获取GetLastError 函数返回的错误代码对应的字符串描述. #include <Windows.h>#include <tchar.h> V ...
- 进入页面就触发了popstate事件。
$(function () { pushHistory(); setTimeout(function () { win ...
- tensorflow/core/kernels/conv_ops.cc:659] check failed: stream->parent()->getc
tensorflow版本与cudnn版本不对应,如tensorflow-gpu==1.1.0,cudnn==6.0 升级tensorflow-gpu到更高版本
- 配置虚拟机 Linux 静态IP
一.查看IP.子网掩码.网关 虚拟网络编辑器 NAT中获取 取消勾选DHCP 二.查看DNS 虚拟机DNS与Windows设置相同 三.配置linux [root@lhs800 ~]# vi /etc ...
- IIS7配置Gzip压缩
II7中自带了gzip功能,理论上应该比ii6配置起来应该简单一点,但是容易出的问题比较多.有的II7配置web服务器角色的时候可能没有安装启用动态内容压缩,所以这个钩子是灰色的,需要再次安装. 如图 ...