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)的更多相关文章

  1. spring集成cxf实现webservice接口功能

    由于cxf的web项目已经集成了Spring,所以cxf的服务类都是在spring的配置文件中完成的.以下是步骤:第一步:建立一个web项目.第二步:准备所有jar包.将cxf_home\lib项目下 ...

  2. 利用MyEclipse开发一个调用webservice接口的程序

    上一篇文章我们已经学习了如何使用Java 工具MyEclipse开发一个webservice接口,那么接口开发好了如何调用?接下来我们就来解决这个问题. 1:首先随便创建一个Java project选 ...

  3. Https Webservice接口的免证书调用

    目录 前言 思路 方案 Axis调用 HttpClient调用 参考链接 前言 在调用https协议的Webservice接口时,如果没有做证书验证,一般会报javax.net.ssl.SSLHand ...

  4. Python的Web编程[2] -> WebService技术[0] -> 利用 Python 调用 WebService 接口

    WebService技术 / WebService Technology 1 关于webservice / Constants WebService是一种跨编程语言和跨操作系统平台的远程调用技术. W ...

  5. 【JMeter4.0学习(三)】之SoapUI创建WebService接口模拟服务端以及JMeter对SOAP协议性能测试脚本开发

    目录: 创建WebService接口模拟服务端 下载SoapUI 新建MathUtil.wsdl文件 创建一个SOAP项目 接口模拟服务端配置以及启动 JMeter对SOAP协议性能测试脚本开发 [阐 ...

  6. Java调用WebService接口实现发送手机短信验证码功能,java 手机验证码,WebService接口调用

    近来由于项目需要,需要用到手机短信验证码的功能,其中最主要的是用到了第三方提供的短信平台接口WebService客户端接口,下面我把我在项目中用到的记录一下,以便给大家提供个思路,由于本人的文采有限, ...

  7. lr使用soap协议,来对webservice接口进行测试

    实际项目中基于WSDL来测试WebService的情况并不多,WSDL并不是WebService测试的最佳选择. 最主要的原因还是因为WSDL文档过于复杂. 在案例(天气预报WebService服务) ...

  8. 通过iTop Webservice接口丰富OQL的功能

    通过Python调用iTop的Webservice接口: #!/usr/bin/env python #coding: utf-8 import requests import json itopur ...

  9. 从xfire谈WebService接口化编程

    前段时间有博友在看我的博文<WebService入门案例>后,发邮件问我关于WebService 接口在java中的开发,以及在实际生产环境中的应用.想想自己入职也有一段时间了,似乎也该总 ...

随机推荐

  1. python css盒子型 浮动

    ########################总结############### 块级标签能够嵌套某些块级标签和内敛标签 内敛标签不能块级标签,只能嵌套内敛标签 嵌套就是: <div> ...

  2. vue this.$router.push和this.$route.path的区别

    this.$router 实际上就是全局路由对象任何页面都可以调用 push(), go()等方法: this.$route  表示当前正在用于跳转的路由器对象,可以调用其name.path.quer ...

  3. CSS3笔记2

    1.CSS样式表分类 <!DOCTYPE html> <html lang="en"> <head> <meta charset=&quo ...

  4. Linux学习笔记:【000】Linux系统入门

    什么是Linux? Linux是一套免费使用和自由传播的类Unix操作系统,是一个基于POSIX(可移植操作系统接口 Portable Operating System Interface of UN ...

  5. Golang入门教程(三)beego 框架安装

    beego 是一个快速开发 Go 应用的 HTTP 框架,他可以用来快速开发 API.Web 及后端服务等各种应用,是一个 RESTful 的框架,主要设计灵感来源于 tornado.sinatra ...

  6. 031、none和host网络的适用场景(2019-02-18 周一)

    参考https://www.cnblogs.com/CloudMan6/p/7053617.html   本节开始,会学习docker的几种原生网络,以及如何创建自定义网络.然后探究容器之间如何通信, ...

  7. Python实现代理模式

    from abc import ABCMeta, abstractmethod NOT_IMPLEMENTED = "You should implement this." cla ...

  8. 学习go语言编程系列之helloworld

    1. 下载https://golang.org/dl/ # Go语言官网地址,在国内下载太慢,甚至都无法访问.通过如下地址下载:https://golangtc.com/download. 2. 安装 ...

  9. 【省时的 IDEA 配置 】 JRebel Mybatis Problems Spring Auto-Scan

    在 Java Web 开发中, 一般更新了 Java 文件后要手动重启 Tomcat 服务器, 才能生效, 浪费不少生命啊, 自从有了 JRebel 这神器的出现, 不论是更新 class 类还是更新 ...

  10. MYSQL ERROR 1045 (28000) Access denied for user (using password YES)问题的解决

    我的Linux是Centos6.7的版本,本机上Mysql突然怎么连接都进不去 报错:MYSQL ERROR 1045 (28000) Access denied for user (using pa ...