阿博泰克杯第五届青少年国际IT精英挑战赛Java组一等奖项目——TimpleShop电商系统_关键代码说明书

原创作者:田超凡(程序员田宝宝)

版权所有,引用请注明原作者,严禁复制转载

TimpleShop关键代码说明书

1.短信验证码功能的代码:

2.js加入购物车的特效 抛物线

3.百度地图定位web

4.银联支付(接口api参考 银联api.txt)

5.  支付宝沙箱对接

6.  QQ登录对接

      7.  IP定位

1.短信验证码功能的代码:

//web平台给的接口用户名

String name="13789998659";

//web平台给的接口密码

String pwd="1531F3D851DE8D880BB499491E0B";

   // 传入进来的电话号码字符串,中间用英文逗号间隔

StringBuffer mobileString=new StringBuffer(phone);

 //生成随机数的代码

int max=99999;

int min=1000;

Random random = new Random();

int s = random.nextInt(max)%(max-min+1) + min;         //将生成的验证码放进缓存里面 方便等下的验证                 ActionContext.getContext().getSession().put("yzm", s);

// 将要发生内容字符串 可自定义

StringBuffer contextString=new StringBuffer("您注册的验证码:"+s+"如非本人操作,请忽略。【TimpleShop】");        

// 签名

String sign="";

// 追加发送时间,可为空,为空为及时发送

String stime="";

// 扩展码,必须为数字 可为空

StringBuffer extno=new StringBuffer();

//然后去调用web平台给的接口方法 dopost 

doPost(name, pwd, mobileString, contextString, sign, stime, extno);

//响应状态值说明

代码

说明

0

提交成功

1

含有敏感词汇

2

余额不足

3

没有号码

4

包含sql语句

10

账号不存在

11

账号注销

12

账号停用

13

IP鉴权失败

14

格式错误

-1

系统异常

//传入以上的参数

public static String doPost(String name, String pwd,

StringBuffer mobileString, StringBuffer contextString,

String sign, String stime, StringBuffer extno) throws Exception {

StringBuffer param = new StringBuffer();

param.append("name="+name);

param.append("&pwd="+pwd);

param.append("&mobile=").append(mobileString);

param.append("&content=").append(URLEncoder.encode(contextString.toString(),"UTF-8"));

param.append("&stime="+stime);

param.append("&sign=").append(URLEncoder.encode(sign,"UTF-8"));

param.append("&type=pt");

param.append("&extno=").append(extno);

//去访问别人的web平台 就是web Service

//UTF-8编码地址为:http://web.cr6868.com/asmx/smsservice.aspx

GB2312编码地址为:http://web.cr6868.com/gbk/smsservice.aspx

URL localURL = new URL("http://web.cr6868.com/asmx/smsservice.aspx?");

//后面就是一些输出流之类的 访问的方式为post

URLConnection connection = localURL.openConnection();

HttpURLConnection httpURLConnection = (HttpURLConnection)connection;

httpURLConnection.setDoOutput(true);

httpURLConnection.setRequestMethod("POST");

httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");

httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

httpURLConnection.setRequestProperty("Content-Length", String.valueOf(param.length()));

OutputStream outputStream = null;

OutputStreamWriter outputStreamWriter = null;

InputStream inputStream = null;

InputStreamReader inputStreamReader = null;

BufferedReader reader = null;

String resultBuffer = "";

try {

outputStream = httpURLConnection.getOutputStream();

outputStreamWriter = new OutputStreamWriter(outputStream);

outputStreamWriter.write(param.toString());

outputStreamWriter.flush();

if (httpURLConnection.getResponseCode() >= 300) {

throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());

}

inputStream = httpURLConnection.getInputStream();

resultBuffer = convertStreamToString(inputStream);

} finally {

if (outputStreamWriter != null) {

outputStreamWriter.close();

}

if (outputStream != null) {

outputStream.close();

}

if (reader != null) {

reader.close();

}

if (inputStreamReader != null) {

inputStreamReader.close();

}

if (inputStream != null) {

inputStream.close();

}

}

return resultBuffer;

}

快递查询功能的代码:

//物流跟踪也是采用web Service

kuaidi=doPost(快递英文名称,快递单号);

//返回值是一个string类型的xml格式的字符串

//需要把节点的信息取出来并且装在string[]里面

Document document = DocumentHelper.parseText(kuaidi);

List<String[]> lists=new ArrayList<String[]>();

for (int i = 1; i < document.getDocument().getRootElement().nodeCount(); i+=2) {

Node node=document.getDocument().getRootElement().node(i);

if(i>3){

String[] item=node.getText().split("-");

lists.add(item);

}

}

addlists=lists;

//这个方法是通过上面短信接口的方法进行改动的

//传入的两个参数

public static String doPost(String Compay, String OrderNo) throws Exception {

StringBuffer param = new StringBuffer();

param.append("Compay="+Compay);

param.append("&OrderNo="+OrderNo);

//Compay=string&OrderNo=string

//这个urlweb Service  有两种访问的方式

//一种是http post 另一种是soap 方式访问

URL localURL = new URL("http://www.gpsso.com/webservice/kuaidi/kuaidi.asmx/KuaidiQuery");

URLConnection connection = localURL.openConnection();

HttpURLConnection httpURLConnection = (HttpURLConnection)connection;

httpURLConnection.setDoOutput(true);

httpURLConnection.setRequestMethod("POST");

httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");

httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

httpURLConnection.setRequestProperty("Content-Length", String.valueOf(param.length()));

OutputStream outputStream = null;

OutputStreamWriter outputStreamWriter = null;

InputStream inputStream = null;

InputStreamReader inputStreamReader = null;

BufferedReader reader = null;

String resultBuffer = "";

try {

outputStream = httpURLConnection.getOutputStream();

outputStreamWriter = new OutputStreamWriter(outputStream);

outputStreamWriter.write(param.toString());

outputStreamWriter.flush();

if (httpURLConnection.getResponseCode() >= 300) {

throw new Exception("HTTP Request is not success, Response code is " + httpURLConnection.getResponseCode());

}

inputStream = httpURLConnection.getInputStream();

resultBuffer = convertStreamToString(inputStream);

} finally {

if (outputStreamWriter != null) {

outputStreamWriter.close();

}

if (outputStream != null) {

outputStream.close();

}

if (reader != null) {

reader.close();

}

if (inputStreamReader != null) {

inputStreamReader.close();

}

if (inputStream != null) {

inputStream.close();

}

}

return resultBuffer;

}

2.js加入购物车的特效 抛物线

//导入一个js 然后去调用里面的一些方法

 // 元素以及其他一些变量

//首先要获取抛物线的落点 也就是侧边栏购物车的位置

var eleFlyElement = document.querySelector("#flyItem"), eleShopCart = document.querySelector(".right_gwd_1");

var numberItem = 0;

// 进行抛物线运动

var myParabola = funParabola(eleFlyElement, eleShopCart, {

speed: 300, //抛物线速度

curvature: 0.0010, //控制抛物线弧度

complete: function() {

eleFlyElement.style.visibility = "hidden";

}

});

// 绑定点击事件

if (eleFlyElement && eleShopCart) {

[].slice.call(document.getElementsByClassName("btnCart")).forEach(function(button) {

button.addEventListener("click", function(event) {

var ss=$(".goods_size_ul li");

var size=$("#ss").text();

//进行尺码判断是否为空

if(ss.length>0){

if(size==0){

alert("您还没有选择尺码!");

}else{

//不为空再去执行那个动画 获取当前的图片路径 赋给当前已经定义好的img

var src = $(".As_big1").attr("src");

$("#flyItem").find("img").attr("src", src);

// 滚动大小

var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft || 0,

scrollTop = document.documentElement.scrollTop || document.body.scrollTop || 0;

eleFlyElement.style.left = event.clientX + scrollLeft + "px";

eleFlyElement.style.top = event.clientY + scrollTop + "px";

eleFlyElement.style.visibility = "visible";

// 让它抛物线完之后,还需要归还原位 目的是用户还会二次点击加入购物车

myParabola.position().move();

}

}else{

var src = $(".As_big1").attr("src");

$("#flyItem").find("img").attr("src", src);

// 抛物线的幅度大小

var scrollLeft = document.documentElement.scrollLeft || document.body.scrollLeft || 0,

scrollTop = document.documentElement.scrollTop || document.body.scrollTop || 0;

eleFlyElement.style.left = event.clientX + scrollLeft + "px";

eleFlyElement.style.top = event.clientY + scrollTop + "px";

eleFlyElement.style.visibility = "visible";

myParabola.position().move();

}

});

});

}

3.百度地图定位web:

//利用JavaScript的方式去访问

<script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=AEO1puS1989e6GtipTugtUyqRZ8NSjqu"></script>

//根据浏览器定位

<script type="text/javascript" >

//创建一个map地图 以下是方法以及参数,返回值介绍

var map = new BMap.Map("allmap");

var point = new BMap.Point(116.331398,39.897445);

map.centerAndZoom(point,12);

var geolocation = new BMap.Geolocation();

geolocation.getCurrentPosition(function(r){

if(this.getStatus() == BMAP_STATUS_SUCCESS){

var mk = new BMap.Marker(r.point);

map.addOverlay(mk);

map.panTo(r.point);

else {

alert('failed'+this.getStatus());

}

},{enableHighAccuracy: true})

//关于状态码

//BMAP_STATUS_SUCCESS 检索成功。对应数值“0”。

//BMAP_STATUS_CITY_LIST  城市列表。对应数值“1”。

//BMAP_STATUS_UNKNOWN_LOCATION  位置结果未知。对应数值“2”。

//BMAP_STATUS_UNKNOWN_ROUTE  导航结果未知。对应数值“3”。

//BMAP_STATUS_INVALID_KEY 非法密钥。对应数值“4”。

//BMAP_STATUS_INVALID_REQUEST   非法请求。对应数值“5”。

//BMAP_STATUS_PERMISSION_DENIED 没有权限。对应数值“6”。(自 1.1 新增)

//BMAP_STATUS_SERVICE_UNAVAILABLE  服务不可用。对应数值“7”。(自 1.1 新增)

//BMAP_STATUS_TIMEOUT 超时。对应数值“8”。(自 1.1 新增)

</script>

页面静态化:

//为了解决高并发的问题采用页面静态化处理

//并且有利于搜索引擎优化SEO

//这个项目采用的

private Logger logger = Logger.getLogger(Httpclient.class);

HttpClient httpClient = null; //HttpClient实例

GetMethod getMethod =null; //GetMethod实例

String page = null;

String webappname = null;

BufferedWriter fw = null;

BufferedReader br = null;

InputStream in = null;

StringBuffer sb = null;

String line = null;

//构造方法

public Httpclient(String webappname){

this.webappname = webappname;

}

/** 根据模版及参数产生静态页面 */

public  boolean createHtmlPage(String url,String htmlFileName){

boolean status = false;

int statusCode = 0;

try{

//创建一个HttpClient实例充当模拟浏览器

httpClient = new HttpClient();

//设置httpclient读取内容时使用的字符集

httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET,"UTF-8");

//创建GET方法的实例

getMethod = new GetMethod(url);

//使用系统提供的默认的恢复策略,在发生异常时候将自动重试3次

getMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, new DefaultHttpMethodRetryHandler());

//设置Get方法提交参数时使用的字符集,以支持中文参数的正常传递

getMethod.addRequestHeader("Content-Type","text/html;charset=UTF-8");

//执行Get方法并取得返回状态码,200表示正常,其它代码为异常

statusCode = httpClient.executeMethod(getMethod);

if (statusCode!=200) {

logger.fatal("静态页面引擎在解析"+url+"产生静态页面"+htmlFileName+"时出错!");

}else{

//读取解析结果

sb = new StringBuffer();

in = getMethod.getResponseBodyAsStream();

br = new BufferedReader(new InputStreamReader(in,"UTF-8"));

while((line=br.readLine())!=null){

sb.append(line+"\n");

}

if(br!=null)br.close();

page = sb.toString();

//将页面中的相对路径替换成绝对路径,以确保页面资源正常访问

page = formatPage(page);

//将解析结果写入指定的静态HTML文件中,实现静态HTML生成

writeHtml(htmlFileName,page);

status = true;

}

}catch(Exception ex){

ex.printStackTrace();

}finally{

//释放http连接

getMethod.releaseConnection();

}

return status;

}

//将解析结果写入指定的静态HTML文件中

private synchronized void writeHtml(String htmlFileName,String page) throws Exception{

fw = new BufferedWriter(new FileWriter(htmlFileName));

OutputStreamWriter fw = new OutputStreamWriter(new FileOutputStream(htmlFileName),"UTF-8");

fw.write(page);

if(fw!=null)fw.close();

}

//将页面中的相对路径替换成绝对路径,以确保页面资源正常访问

private String formatPage(String page){

page = page.replaceAll("\\.\\./\\.\\./\\.\\./", webappname+"/");

page = page.replaceAll("\\.\\./\\.\\./", webappname+"/");

page = page.replaceAll("\\.\\./", webappname+"/");

return page;

}

//测试方法

public static void main(String[] args){

Httpclient h = new Httpclient("webappname");

h.createHtmlPage("http://localhost:8080/TimpleShop/AS_home_getBrand.action","D:/TimpleShop/TimpleShop/WebRoot/jsp/Httpclient/home.html");

System.out.println("静态页面已经生成");

}

}

4.银联支付(接口api参考 银联api.txt)

基于Servlet的接口,接受用户传入参数生成自动跳转的Html表单,返回响应报文到回调地址;

protected void doPost(HttpServletRequest req, HttpServletResponse resp)

           throws ServletException, IOException {

       /**

        * 请求银联接入地址,获取证书文件,证书路径等相关参数初始化到SDKConfig类中

        * java main 方式运行时必须每次都执行加载

        * 如果是在web应用开发里,这个方法可使用监听的方式写入缓存,无须在这出现

        */

       //这里已经将加载属性文件的方法挪到了web/AutoLoadServlet.java

       //SDKConfig.getConfig().loadPropertiesFromSrc(); //classpath加载acp_sdk.properties文件

      

       //前台页面传过来的

       String merId = req.getParameter("merId");

       String txnAmt = req.getParameter("txnAmt");

       String userid=req.getParameter("userid");

       String addid=req.getParameter("addid");

       Map<String, String> requestData = new HashMap<String, String>();

      

       /***银联全渠道系统,产品参数,除了encoding自行选择外其他不需修改***/

       requestData.put("version", DemoBase.version);            //版本号,全渠道默认值

       requestData.put("encoding", DemoBase.encoding_UTF8);             //字符集编码,可以使用UTF-8,GBK两种方式

       requestData.put("signMethod", "01");                       //签名方法,只支持 01RSA方式证书加密

       requestData.put("txnType", "02");                          //交易类型 02:预授权

       requestData.put("txnSubType", "01");                       //交易子类型, 01:预授权

       requestData.put("bizType", "000201");                      //业务类型,B2C网关支付,手机wap支付

       requestData.put("channelType", "07");                      //渠道类型,这个字段区分B2C网关支付和手机wap支付;07PC,平板  08:手机

      

       /***商户接入参数***/

       requestData.put("merId", merId);                           //商户号码,请改成自己申请的正式商户号或者open上注册得来的777测试商户号

       requestData.put("accessType", "0");                        //接入类型,0:直连商户

       requestData.put("orderId",DemoBase.getOrderId());             //商户订单号,8-40位数字字母,不能含“-”“_”,可以自行定制规则    

       requestData.put("txnTime", DemoBase.getCurrentTime());        //订单发送时间,取系统时间,格式为YYYYMMDDhhmmss,必须取当前时间,否则会报txnTime无效

       requestData.put("currencyCode", "156");                  //交易币种(境内商户一般是156 人民币)    

       requestData.put("txnAmt", txnAmt);                             //交易金额,单位分,不要带小数点

       requestData.put("reqReserved", userid+","+addid);                     //请求方保留域,如需使用请启用即可;透传字段(可以实现商户自定义参数的追踪)本交易的后台通知,对本交易的交易状态查询交易、对账文件中均会原样返回,商户可以按需上传,长度为1-1024个字节     

      

       //前台通知地址 (需设置为外网能访问 http https均可),支付成功后的页面 点击返回商户按钮的时候将异步通知报文post到该地址

       //如果想要实现过几秒中自动跳转回商户页面权限,需联系银联业务(发邮件到operation@unionpay.com)申请开通自动返回商户权限

       //异步通知参数详见open.unionpay.com帮助中心 下载  产品接口规范  网关支付产品接口规范 消费交易 商户通知

       requestData.put("frontUrl", DemoBase.frontUrl);

      

       //后台通知地址(需设置为【外网】能访问 http https均可),支付成功后银联会自动将异步通知报文post到商户上送的该地址,失败的交易银联不会发送后台通知

       //后台通知参数详见open.unionpay.com帮助中心 下载  产品接口规范  网关支付产品接口规范 消费交易 商户通知

       //注意:1.需设置为外网能访问,否则收不到通知    2.http https均可  3.收单后台通知后需要10秒内返回http200302状态码

       //    4.如果银联通知服务器发送通知后10秒内未收到返回状态码或者应答码非http200,那么银联会间隔一段时间再次发送。总共发送5次,每次的间隔时间为0,1,2,4分钟。

       //    5.后台通知地址如果上送了带有?的参数,例如:http://abc/web?a=b&c=d 在后台通知处理程序验证签名之前需要编写逻辑将这些字段去掉再验签,否则将会验签失败

       requestData.put("backUrl", DemoBase.backUrl);

      

        //

       //

       //       报文中特殊用法请查看 PC wap网关跳转预授权特殊用法.txt

       //

        //

      

       /**请求参数设置完毕,以下对请求参数进行签名并生成html表单,将表单写入浏览器跳转打开银联页面**/

       Map<String, String> submitFromData = AcpService.sign(requestData,DemoBase.encoding_UTF8);  //报文中certId,signature的值是在signData方法中获取并自动赋值的,只要证书配置正确即可。

       String requestFrontUrl = SDKConfig.getConfig().getFrontRequestUrl();  //获取请求银联的前台地址:对应属性文件acp_sdk.properties文件中的acpsdk.frontTransUrl

       String html = AcpService.createAutoFormHtml(requestFrontUrl, submitFromData,DemoBase.encoding_UTF8);   //生成自动跳转的Html表单

      

       LogUtil.writeLog("打印请求HTML,此为请求报文,为联调排查问题的依据:"+html);

       //将生成的html写到浏览器中完成自动跳转打开银联支付页面;这里调用signData之后,将html写到浏览器跳转到银联页面之前均不能对html中的表单项的名称和值进行修改,如果修改会导致验签不通过

       resp.getWriter().write(html);

    }

交易成功的响应报文:

交易失败会自动回调error;

5.支付宝

配置支付宝的系统参数:

// 应用ID,您的APPID,收款账号既是您的APPID对应支付宝账号

    public static String app_id = "2016080200150129";

    // 商户私钥,您的PKCS8格式RSA2私钥

    public static String merchant_private_key = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCT9Yi7zFul4bvcrvaj1ILMjOsUdThY5q2U/UDuCVkPlhlGmXws1Rtai9eJNSFbLWZnysya5faph5A8QaGzfBKFy8ej6bME6KCva2n5T4VKQkP3tDz1DQSN4pYB0BuMBBE8HNzCv2WZzf+bVU32WcVebAdhJRchOmQeyhVpGxEjGoiTgX0ziKh2E7/mcq0lSonksJorXOnZGQaPHvWiU2FH6BmKhOzz++WHQfz6ApZ2nrBhyYf8q/xQiryTZfEvZRDGS6VVWrR2c6CCBUlHYJ8pic0YBe0LfIdF+XVvLgG3kk9SFnsiYFroReDDAo+2+GcR5EA5Q0d4RV2wHdMpSyapAgMBAAECggEAJ0Rlqnmc5RRYmEPy/x3aLNFFXmORtb5a2QyxW7stYL6ULLF1TCyumsQ8SpTIKnuNDwS6cm2PngR1WhiNAqZuAAZKEI1oTmgypPub32ekV0Xo5ed2ug5fZAx7hTWm6ez2af669BB5tWz/ZkkobLX8dIe1GaoPTmlBww4cyo09ahQr7qCPZ2SXBxXI3UijxbSvPJzVUA2DCe6VDoULPWF6OQQmsbSDlX+pF6zHA6o+6KvhsGjYQtUmW+R5erICr0f4uAbRReciVycCv5nJQ7Jp3y4IS6MJK2YL5/mlqVglb2uWOKH3QicF5MeEhTBJwW87xMWSpYYU8GtJgwvWwVUkFQKBgQDUuUrzlTbwK/q9Hb9QxnT29QNGbXIRkSF5jWYJTUJMIXXWhk4t/pp2eOI7S//ffw45XjbyOS04FXnlmUIs27RP8i99uFYxiEdL288CKyqAppPUwzIt1XysNkm4D+6VeUfXr/OLaAjLwSIZ/l/vbolFE7QzdIh72nzhcMDV+KXNfwKBgQCyD0frdBO4FpIdsEKo8jCYK/LUS6UfJPyOJz0OJjjBRsrQHFlnZchd461qkZmWFkU0HSGB0yKNSSOhQHj3kppHKjhsuJvjaAXjIXUZPXNelmQHSlAuNkLdZrWPFRGqgl0qSLfrWtB8elo7EFXtsSRjkGWaxZKXl/OGAEJ0Uc7v1wKBgQCM0lE86WXiHqsxsNSq64YYymAtqlxeJr6LUkDfHYcrEOeKaYStzCODFElnycsMsHbBIY6sUY+O1iDJDukQ+yzl08T+rB5bUgUowc3LeLn9SskIi2PXlcGf25x3vgxKZWxa678FZYyVHjiuDoiB36H92apsedO0chJDx7nQrHdOjwKBgAe17bFeh3QTViR++4QBaOVOEefrlqzwlxc4z8YLFa4Y+LNmZuC5YaHfOCVDRNlhAYIuOMM8d2SS5D4ZYqOl75RhWawrmmSQnqClVELRjGtuK8q9BxfZNbAMwJP/n5I4rvwjxgMlHZ4mVj30iSQP5bmCCURYhe6Wn+8Pl9Edsc5lAoGAW614LCuioRJ2LSi/XpFfkWI79tOLWMX8NT+R61ii1l0pvXl4WOQ6sBnUDlT7is0yzdbLZjZhtDgJPojFDgLw7Occ0ul4v73f2drGTi7cCdv0SKDU8F6m6PnwP2hMcCPVNZDiCe1WPUnu6Ow+UM76wZ9kXs41rlGHw04aNm90EPc=";

    // 支付宝公钥,查看地址:https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。

    public static String alipay_public_key = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAtPP9ITQulLJjrQTP3EoYXDYig2UltHIipF/LnI6Ck1iko41sKyZIYdVTgur9EKQ/t0x1/843boxeYfvkXeCwzuPwdzDpk5U9fg7+I9XALCi1c7Ikscs5RzcHPU9nyoStgOblhbsEFkjhB92yWZmhyEMPX+7SH1cEGVoXdg5UQ2i5+wIncCfeWxbwV5P3wpNtRMxBb5lOxgxEGlFGllRXFlSwe1/p5j4jcbH6bghmLptjv7h2SF0sGbXkTs1eCoxPlXTxCkg0cMu8ryIJ9pfxz78jZvdmma1CAQgiGuYKSsT0eksAJF66EBoEJUvUygxMY6DKqFZvkZ50LW3iWDaCcQIDAQAB";

    // 服务器异步通知页面路径  http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问

    public static String notify_url = "http://localhost:8080/TimpleShop/notify_url.jsp";

    // 页面跳转同步通知页面路径 http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问

    public static String return_url = "http://localhost:8080/TimpleShop/return_url.jsp";

    // 签名方式

    public static String sign_type = "RSA2";

    // 字符编码格式

    public static String charset = "utf-8";

    // 支付宝网关

    public static String gatewayUrl = "https://openapi.alipaydev.com/gateway.do";

    // 支付宝网关

    public static String log_path = "C:\\";

获取用户的自定义参数加上封装好的系统参数,生成签名后的请求报文,请求支付宝接口:

//获得初始化的AlipayClient

    AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

   

    //设置请求参数

    AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();

    alipayRequest.setReturnUrl(AlipayConfig.return_url);

    alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

   

    //商户订单号,商户网站订单系统中唯一订单号,必填

    String out_trade_no = new String(request.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"),"UTF-8");

    //付款金额,必填

    String total_amount = new String(request.getParameter("WIDtotal_amount").getBytes("ISO-8859-1"),"UTF-8");

    //订单名称,必填

    String subject = new String(request.getParameter("WIDsubject").getBytes("ISO-8859-1"),"UTF-8");

    //商品描述,可空

    String body = new String(request.getParameter("WIDbody").getBytes("ISO-8859-1"),"UTF-8");

    alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","

            + "\"total_amount\":\""+ total_amount +"\","

           + "\"subject\":\""+ subject +"\","

           + "\"body\":\""+ body +"\","

           + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

   

    //若想给BizContent增加其他可选请求参数,以增加自定义超时时间参数timeout_express来举例说明

    //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","

    //      + "\"total_amount\":\""+ total_amount +"\","

    //      + "\"subject\":\""+ subject +"\","

    //      + "\"body\":\""+ body +"\","

    //      + "\"timeout_express\":\"10m\","

    //      + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

    //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

    String result = alipayClient.pageExecute(alipayRequest).getBody();

    //输出

    out.println(result);

对应api参考

页面回调

提交订单的请求参数

6.QQ登录

首先到QQ开发平台注册应用等信息,获取appid

JS:

<script type="text/javascript"

src="http://qzonestyle.gtimg.cn/qzone/openapi/qc_loader.js" data-appid="101394710" data-redirecturi="http://localhost:8080/TimpleShop/qq.jsp" charset="utf-8"></script>

    //通过QQjs,将指定的节点变成QQ登录按钮

       QC.Login({

       btnId:"qqLoginBtn"  //插入按钮的节点id

   

});

//使用自定义的QQ登录按钮,绑定登录的功能

function qq(){

    $("#qqLoginBtn a").trigger('click');

    QQreg();

}

//实时获取登录状态

function QQreg(){

    var image= $(".figure img").attr("src");

    var name=$(".nickname").text();

    if(image==undefined){

    setTimeout(QQreg,1000);

    }else{

        jQuery.ajax({

               url : 'As_user_login1.action',

               data : {"image":image,"username":name},

               type : "POST",

               beforeSend : function() {

                  

               },

               success : function(data) {

               var js=$.parseJSON(data);

                   if(js.user_id!=0){

                  

                       callback();

                   }else{

                       $(".userpwd").val("");

                       $(".userlogin").val("");

                   }

               }

           });

       

    }

}

//注销登录

QC.Login.signOut();

7.IP定位

首先通过请求头得到访问者的ip;

public String addAddress() throws NumberFormatException, JSONException, UnsupportedEncodingException, UnknownHostException{

               String ip = ServletActionContext.getRequest().getHeader("X-Real-IP");

                if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {

                   

               }

               ip = ServletActionContext.getRequest().getHeader("X-Forwarded-For");

               if (!StringUtils.isBlank(ip) && !"unknown".equalsIgnoreCase(ip)) {

                   // 多次反向代理后会有多个IP值,第一个为真实IP

                   int index = ip.indexOf(',');

                     if (index != -1) {

                        ip= ip.substring(0, index);

                     } else {

                      

                   }

                } else {

           ip= ServletActionContext.getRequest().getRemoteAddr();

                }

//判断IP和服务器地址是否一致,一致就返回服务器所在真实地址;

          if (ip.equals(ServletActionContext.getRequest().getLocalAddr())||ip.equals("0:0:0:0:0:0:0:1")) {

              addressSF="湖北省";

              addressCS="武汉市";

              addressDQ="洪山区";

       }else{

//否则调用淘宝接口,查询IP对应的真实地址,查完后将省,市,县返回页面

           String address=new AddressUtils().getAddresses("ip="+InetAddress.getLocalHost(), "utf-8");

           String[] addresss=address.split("=");

             addressSF=addresss[0];

              addressCS=addresss[1];

              addressDQ=addresss[2];

       }

淘宝查地址接口:

/**

 *  根据IP地址获取详细的地域信息

 *  @project:personGocheck

 *  @class:AddressUtils.java

 *  @author:heguanhua E-mail:37809893@qq.com

 *  @dateNov 14, 2012 6:38:25 PM

 */ 

public class AddressUtils {  

 /**

  *

  * @param content

  *            请求的参数 格式为:name=xxx&pwd=xxx

  * @param encoding

  *            服务器端请求编码。如GBK,UTF-8

  * @return

  * @throws UnsupportedEncodingException

  */ 

 public String getAddresses(String content, String encodingString) 

   throws UnsupportedEncodingException { 

  // 这里调用pconline的接口 

  String urlStr = "http://ip.taobao.com/service/getIpInfo.php"

  // http://whois.pconline.com.cn取得IP所在的省市区信息 

  String returnStr = this.getResult(urlStr, content, encodingString); 

  if (returnStr != null) { 

   // 处理返回的省市区信息 

   String[] temp = returnStr.split(","); 

   if(temp.length<3){ 

    return "0";//无效IP,局域网测试 

   } 

   String region = (temp[5].split(":"))[1].replaceAll("\"", ""); 

   region = decodeUnicode(region);// 省份 

   

            String country = ""

            String area = ""

            // String region = ""; 

            String city = ""

            String county = ""

            String isp = ""

            for (int i = 0; i < temp.length; i++) { 

                switch (i) { 

                case 1: 

                    country = (temp[i].split(":"))[2].replaceAll("\"", ""); 

                    country = decodeUnicode(country);// 国家 

                    break

                    case 3: 

                        area = (temp[i].split(":"))[1].replaceAll("\"", ""); 

                        area = decodeUnicode(area);// 地区  

                    break

                    case 5: 

                        region = (temp[i].split(":"))[1].replaceAll("\"", ""); 

                        region = decodeUnicode(region);// 省份  

                    break;  

                    case 7: 

                        city = (temp[i].split(":"))[1].replaceAll("\"", ""); 

                        city = decodeUnicode(city);// 市区 

                    break;  

                    case 9: 

                            county = (temp[i].split(":"))[1].replaceAll("\"", ""); 

                            county = decodeUnicode(county);// 地区  

                    break

                    case 11: 

                        isp = (temp[i].split(":"))[1].replaceAll("\"", ""); 

                        isp = decodeUnicode(isp); // ISP公司 

                    break

                } 

            } 

    

            region=region+"="+city+"="+county; 

   return region; 

  } 

  return null

 } 

 /**

  * @param urlStr

  *            请求的地址

  * @param content

  *            请求的参数 格式为:name=xxx&pwd=xxx

  * @param encoding

  *            服务器端请求编码。如GBK,UTF-8

  * @return

  */ 

 private String getResult(String urlStr, String content, String encoding) { 

  URL url = null

  HttpURLConnection connection = null

  try

   url = new URL(urlStr); 

   connection = (HttpURLConnection) url.openConnection();// 新建连接实例 

   connection.setConnectTimeout(2000);// 设置连接超时时间,单位毫秒 

   connection.setReadTimeout(2000);// 设置读取数据超时时间,单位毫秒 

   connection.setDoOutput(true);// 是否打开输出流 true|false 

   connection.setDoInput(true);// 是否打开输入流true|false 

   connection.setRequestMethod("POST");// 提交方法POST|GET 

   connection.setUseCaches(false);// 是否缓存true|false 

   connection.connect();// 打开连接端口 

   DataOutputStream out = new DataOutputStream(connection 

     .getOutputStream());// 打开输出流往对端服务器写数据 

   out.writeBytes(content);// 写数据,也就是提交你的表单 name=xxx&pwd=xxx 

   out.flush();// 刷新 

   out.close();// 关闭输出流 

   BufferedReader reader = new BufferedReader(new InputStreamReader( 

     connection.getInputStream(), encoding));// 往对端写完数据对端服务器返回数据 

   // ,BufferedReader流来读取 

   StringBuffer buffer = new StringBuffer(); 

   String line = ""

   while ((line = reader.readLine()) != null) { 

    buffer.append(line); 

   } 

   reader.close(); 

   return buffer.toString(); 

  } catch (IOException e) { 

   e.printStackTrace(); 

  } finally

   if (connection != null) { 

    connection.disconnect();// 关闭连接 

   } 

  } 

  return null

 } 

 /**

  * unicode 转换成 中文

  *

  * @author fanhui 2007-3-15

  * @param theString

  * @return

  */ 

 public static String decodeUnicode(String theString) { 

  char aChar; 

  int len = theString.length(); 

  StringBuffer outBuffer = new StringBuffer(len); 

  for (int x = 0; x < len;) { 

   aChar = theString.charAt(x++); 

   if (aChar == '\\') { 

    aChar = theString.charAt(x++); 

    if (aChar == 'u') { 

     int value = 0; 

     for (int i = 0; i < 4; i++) { 

      aChar = theString.charAt(x++); 

      switch (aChar) { 

      case '0'

      case '1'

      case '2'

      case '3'

      case '4'

      case '5'

      case '6'

      case '7'

      case '8'

      case '9'

       value = (value << 4) + aChar - '0'

       break

      case 'a'

      case 'b'

      case 'c'

      case 'd'

      case 'e'

      case 'f'

       value = (value << 4) + 10 + aChar - 'a'

       break

      case 'A'

      case 'B'

      case 'C'

      case 'D'

      case 'E'

      case 'F'

       value = (value << 4) + 10 + aChar - 'A'

       break

      default

       throw new IllegalArgumentException( 

         "Malformed      encoding."); 

      } 

     } 

     outBuffer.append((char) value); 

    } else

     if (aChar == 't') { 

      aChar = '\t'

     } else if (aChar == 'r') { 

      aChar = '\r'

     } else if (aChar == 'n') { 

      aChar = '\n'

     } else if (aChar == 'f') { 

      aChar = '\f'

     } 

     outBuffer.append(aChar); 

    } 

   } else

    outBuffer.append(aChar); 

   } 

  } 

  return outBuffer.toString(); 

 } 

页面通过QQ提供的JS省市区三级联动

<script type="text/javascript" src="js/geo.js"></script>

//这个函数是必须的,因为在geo.js里每次更改地址时会调用此函数

function promptinfo()

{

    var s1 = document.getElementById('s1');

    var s2 = document.getElementById('s2');

    var s3 = document.getElementById('s3');

        /* $("#s2 option[value='武汉市']").attr("selected","selected"); */

  

}

$(function(){

          

            $("form").addClass('animated  lightSpeedIn');

        var SF=$("#addresssf").text();

        var CS=$("#addresscs").text();

        var DQ=$("#addressdq").text();

        setup();

        preselect(SF,0);

        for(var i=0;i<$("#s2 option").length;i++){

           if($($("#s2 option").get(i)).val()==CS){

                document.getElementById(s[1]).selectedIndex = i;

                change(2);

           }

          

        }

        for(var i=0;i<$("#s3 option").length;i++){

           if($($("#s3 option").get(i)).val()==DQ){

                document.getElementById(s[2]).selectedIndex = i;

                change(3);

           }

          

        }

        promptinfo();

});

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/758483.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

2024学习鸿蒙开发,未来发展如何?

一、前言 想要了解一个领域的未来发展如何&#xff0c;可以从如下几点进行&#xff0c;避免盲从&#xff1a; 国家政策落地情况就业市场如何学习 通过上述三点&#xff0c;就能分析出一个行业的趋势。大家可以看到&#xff0c;我上面的总体逻辑就是根据国家政策来分析未来方…

代码随想录day24(2)二叉树:合并二叉树(leetcode617)

题目要求&#xff1a;将两个二叉树合并&#xff0c;要求是将同位置处的两个节点值相加&#xff0c;如果一个为空那就将另一个二叉树的值覆盖。 思路&#xff1a;如果使用迭代法&#xff0c;就是通过层序遍历&#xff0c;通过队列进行判断进行相加。如果使用递归法&#xff0c;…

git基础-获取git仓库

通过本章的学习&#xff0c;应该能够配置和初始化一个仓库&#xff0c;开始和停止跟踪文件&#xff0c;暂存和提交更改。我们还将展示如何设置 Git 来忽略特定的文件和文件模式&#xff0c;如何快速轻松地撤销错误&#xff0c;如何浏览项目的历史记录并查看提交之间的更改&…

酷开科技聚焦大屏端数据研究,构建酷开系统深度挖掘大屏商业价值

中国所有的彩色大屏中&#xff0c;智能电视规模已经过半&#xff0c;OTT平台的数据价值越发引起人们关注。作为OTT行业的头部代表&#xff0c;酷开科技一直聚焦大屏端数据研究&#xff0c;目前已经形成一套基于大屏指数的智慧营销体系&#xff0c;让OTT大屏的数字营销化水平实现…

AI:150-基于深度学习的医学数据挖掘与病症关联发现

🚀点击这里跳转到本专栏,可查阅专栏顶置最新的指南宝典~ 🎉🎊🎉 你的技术旅程将在这里启航! 从基础到实践,深入学习。无论你是初学者还是经验丰富的老手,对于本专栏案例和项目实践都有参考学习意义。 ✨✨✨ 每一个案例都附带关键代码,详细讲解供大家学习,希望…

ModuleNotFoundError: No module named ‘torch_geometric‘

1. 解决办法——安装库 pip install torch_geometric -i https://pypi.tuna.tsinghua.edu.cn/simple总结 如果你仍然遇到问题&#xff0c;请确保你的pip或conda是最新版本&#xff0c;并且你正在使用的Python环境是激活的。此外&#xff0c;如果你的PyTorch版本与 torch_geom…

Anconda 在无网络的情况下安装想要的python环境

###windows python anconda 一、实现步骤 1、在本地安装好自己想要的python环境 2、下载conda-pack环境打包工具 conda-pack 3、将虚拟环境打包&#xff0c;将虚拟环境和Anaconda安装包拷贝到离线服务器上 4、安装Anaconda,并将虚拟环境移植到离线服务器上anaconda/envs/目…

吴恩达机器学习-可选实验室:简单神经网络(Simple Neural Network)

在这个实验室中&#xff0c;我们将使用Tensorflow构建一个小型神经网络 import numpy as np import matplotlib.pyplot as plt plt.style.use(./deeplearning.mplstyle) import tensorflow as tf from tensorflow.keras.models import Sequential from tensorflow.keras.laye…

win10 配置 oh-my-posh

win10 配置 oh-my-posh 0. 前置1. 安装1.1. 软件1.2. 字体1.3. 激活1.3.1. Git Bash1.3.2. PowerShell 2. 配置2.1. 效果2.2. 说明2.3. 其他2.3.1. 新版PowerShell2.3.2 conda问题 0. 前置 这个东西毕竟是个&#xff0c;命令行美化工具&#xff0c;所以需要先有一个命令行&…

芯片与针灸

所有观点&#xff0c;全是个人猜测&#xff0c;未得到科学证实&#xff0c;请注意识别 文章目录 前言一、Trimming 是什么&#xff1f;二、获取步骤1.扎针2.针灸 总结 前言 芯片的出厂过程中&#xff0c;有一个步骤叫做 trimming&#xff1a;意思就是调整芯片的性能参数&#…

Java中的可变参数

java提供了可变参数这个语法。 可变参数本质为数组。 一般可变参数应用于形参中。用于接收实参。 此时实参可以有多种形式。 一种是最正常的&#xff0c;实参为数组名。 public class Date1 {public void one(int ... arr){int sum0;for (int x:arr){sumx;}System.out.pri…

eth uniswap 套利交易案例四

交易hash: 0x085843b47c0d1b0f820b80c166ea8dd2e3928876fb353d107e49dcf879cf8426 交易时间&#xff1a; 2024.02.29 获利&#xff1a; 196,284刀 balancer 借了 338个 weth&#xff0c; 然后和 0x3BA6A019eD5541b5F5555d8593080042Cf3ae5f4 交易用 282个weth 换了293个wste…

【矩阵】54. 螺旋矩阵【中等】

螺旋矩阵 给你一个 m 行 n 列的矩阵 matrix &#xff0c;请按照 顺时针螺旋顺序 &#xff0c;返回矩阵中的所有元素。 示例 1&#xff1a; 输入&#xff1a;matrix [[1,2,3],[4,5,6],[7,8,9]] 输出&#xff1a;[1,2,3,6,9,8,7,4,5] 解题思路 1、模拟顺时针螺旋顺序遍历矩阵…

名词【语法笔记】

1.名词分为几大类 2.每一类&#xff0c;又有几个小类&#xff0c;以及所需要注意什么

【每日力扣】131.分割回文串与450.删除二叉搜索树中的节点

&#x1f525; 个人主页: 黑洞晓威 &#x1f600;你不必等到非常厉害&#xff0c;才敢开始&#xff0c;你需要开始&#xff0c;才会变的非常厉害。 131.分割回文串 给你一个字符串 s&#xff0c;请你将 s 分割成一些子串&#xff0c;使每个子串都是 回文串 。返回 s 所有可能的…

ROS多机通信

在充分的单机学习测试之后&#xff0c;往往要进行真实机器人的测试&#xff0c;那么就要接触到多机通信的问题。ROS采用的分布式网络通信&#xff0c;只要正确的设置ROS_MASTER_URI和ROS_IP两个环境变量&#xff0c;就可以成功实现ROS的多机通信&#xff0c;有时我们也称之为主…

Linux系统——Mysql数据库操作

目录 一、数据库基本操作 1.查看数据库结构 1.1查看数据库信息——Show databases 1.2查看数据库中的表信息——Show tables Show tables in 数据库名 use 数据库名 show tables 1.3显示数据表的结构&#xff08;字段&#xff09;——Describe&#xff08;Desc&#x…

+-x c++

描述 我们有两个整数&#xff1a;A 和 B。 请打印出AB、A−B和AB中最大的数。 输入描述 A B 输出描述 打印 AB、A−B 和 AB 中最大的数字。 用例输入 1 -13 3用例输出 1 -10用例输入 2 1 -33用例输出 2 34用例输入 3 13 3用例输出 3 39提示 样本输出 1 AB…

child_process

Node.js 中的 child_process 模块提供了一系列用于创建和管理子进程的API。这里列出一些常用的API及其使用示例&#xff1a; 1. child_process.exec() 异步执行命令并收集其输出&#xff0c;适合简单命令。 const { exec } require(child_process);exec(ls -l, (error, std…

HarmonyOS(鸿蒙)ArkUI组件

方舟开发框架&#xff08;简称ArkUI&#xff09;为HarmonyOS应用的UI开发提供了完整的基础设施&#xff0c;包括简洁的UI语法、丰富的UI功能&#xff08;组件、布局、动画以及交互事件&#xff09;&#xff0c;以及实时界面预览工具等&#xff0c;可以支持开发者进行可视化界面…