package com.j1.mai.action;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONObject; import org.apache.log4j.Logger;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody; import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.j1.base.type.MsgStatus;
import com.j1.mai.model.common.SoaApiBaseAction;
import com.j1.mai.util.PropertyConfigurer;
import com.j1.soa.common.DateUtils;
import com.j1.soa.common.Md5Util; @Controller
@Scope("request")
@RequestMapping("/storeConsumptionLogin")
public class StoreLoginAction extends SoaApiBaseAction {
// final static String url ="http://localhost:8080/httpServer/c_i/common_i"; static Logger LOG = Logger.getLogger(StoreLoginAction.class); @RequestMapping("/login") public Object loginStoreConsumption(
HttpServletRequest request,
HttpServletResponse response,
@RequestParam(value = "empName", required = true) String empName,// 用户名
@RequestParam(value = "loginPassWd", required = true) String loginPassWd// 密码
) {
/**
* 调用接口
*/ Map<String, Object> mapRes = new HashMap<String, Object>();
// 读取配置文件
String promoteUrl =(String)PropertyConfigurer.getString("storeConsumptiondLoginUrl");
String message = null;
JSONObject jsonObject = null;
message = httpSend(promoteUrl, empName, loginPassWd);
try { // 解析json字符串
message = message.replaceAll("\\\\", "");
String jsonStr = message.substring(message.indexOf("[") + 1,
message.indexOf("]"));
jsonObject = JSONObject.fromObject(jsonStr);
String responseCode = jsonObject.getString("msg");
if (responseCode.equals("用户名或密码错误")) {
mapRes.put("status", 1);
mapRes.put("msg", "loginFalse");
} else {
mapRes.put("status", 0);
mapRes.put("msg", "ok"); } } catch (Exception e) { e.printStackTrace();
} finally {
/**
*将操作的个人信息存在Session中,传给前台
*以便于在前台在录入会员的时候传递到后台
*/
//操作人名称
String empNameAdd=jsonObject.getString("empName");
//操作门店名称
String deptNameAdd=jsonObject.getString("deptName");
//门店编码
String deptNo=jsonObject.getString("deptNo");
//登录名
String loginName=jsonObject.getString("loginName");
//操作人ID
String empId=jsonObject.getString("empId");
request.getSession().setAttribute("empNameAdd", empNameAdd);
request.getSession().setAttribute("deptNameAdd", deptNameAdd);
request.getSession().setAttribute("deptNo",deptNo );
request.getSession().setAttribute("empId", empId);
request.getSession().setAttribute("loginName", loginName);
// this.write(request, response); } JSON o=(JSON) com.alibaba.fastjson.JSONObject.toJSON(mapRes);
System.out.println("查看=============="+o);
return com.alibaba.fastjson.JSONObject.toJSON(mapRes); } /**
* 发送HTTP请求
*
* @param url
* @param propsMap
* 发送的参数
*/ public String httpSend(String promoteUrl, String empName, String loginPassWd) {
StringBuffer buffer = new StringBuffer();
String responseContent = null;
try { URL url_new = new URL(promoteUrl);// 创建连接
HttpURLConnection connection = (HttpURLConnection) url_new
.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("POST");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
connection.connect();
// POST请求
DataOutputStream out = new DataOutputStream(
connection.getOutputStream()); // utf-8编码 ; String sign = null;
String time = DateUtils.longToDateAll(System.currentTimeMillis());
String token = "91A1643059824847938125BA0AC0F557"; // token 不产于传送
String format = "json"; // 传送方式
String method = "queryTbl_Employee";// 调用方法
String sessionKey = "123456789078945";// sessionkey
String up_date = time;// 上传日期 yyyy-mm-dd
String version = "1.0.2";// 版本号
try {
sign = Md5Util.Bit32(format + method + sessionKey + token
+ up_date + version);
} catch (Exception e1) { e1.printStackTrace();
}
JSONObject obj = new JSONObject();
obj.element("sessionKey", sessionKey);
obj.element("method", method);
obj.element("format", format);
obj.element("up_Date", time);
obj.element("sign", sign);
obj.element("version", version);
JSONObject objbusinessdate = new JSONObject();
objbusinessdate.element("username", empName);// username ,
objbusinessdate.element("password", loginPassWd); // password
obj.element("businessData", objbusinessdate); System.out.println(obj.toString());
out.writeBytes(obj.toString()); out.flush();
// 读取响应
int length = (int) connection.getContentLength();// 获取长度
System.out.println("length:" + length); if (connection.getResponseCode() != HttpURLConnection.HTTP_OK) {
System.out.println("网络错误异常!!!!");
}
InputStream in = connection.getInputStream();
BufferedReader rds = new BufferedReader(new InputStreamReader(in,
"UTF-8"));
String tempLine = rds.readLine(); StringBuffer tempStr = new StringBuffer();
if (tempLine != null) {
tempStr.append(tempLine);
tempLine = rds.readLine();
}
responseContent = tempStr.toString(); // BufferedReader rd = new BufferedReader(new InputStreamReader(
// connection.getInputStream(), "UTF-8"));
// while( (responseMsg = rd.readLine())!=null){
// buffer.append(responseMsg);
//
// } out.close();
rds.close(); connection.disconnect();
System.out.println(" Buffer============= " + buffer.toString());
return responseContent;
} catch (IOException e) {
e.printStackTrace();
}
// return buffer.toString(); // 自定义错误信息
return responseContent; // 自定义错误信息
}
}

用IO流发送Http请求的更多相关文章

  1. 通过http流发送post请求

    一般都是用curl扩展来完成,看了手册的通过stream的方式更加简单. 请求脚本stream.php $url = 'http://localhost/stream_api.php'; $body ...

  2. 非阻塞IO发送http请求

    import socket from urllib.parse import urlparse from selectors import DefaultSelector, EVENT_READ, E ...

  3. Java发送socket请求的工具

    package com.tech.jin.util; import java.io.ByteArrayOutputStream; import java.io.IOException; import ...

  4. 如何在WinForm中发送HTTP请求

    如何在WinForm中请求发送HTTP 手工发送HTTP请求主要是调用 System.Net的HttpWebResponse方法 手工发送HTTP的GET请 求: string strURL = &q ...

  5. Java基础知识强化之IO流笔记71:NIO之 NIO的(New IO流)介绍

    1. I/O 简介 I/O ( 输入/输出  ):指的是计算机与外部世界或者一个程序与计算机的其余部分的之间的接口.它对于任何计算机系统都非常关键,因而所有 I/O 的主体实际上是内置在操作系统中的. ...

  6. C#后台发送HTTP请求

    using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using Syst ...

  7. 通过java.net.URLConnection发送HTTP请求的方法

    一.前言 如何通过Java发送HTTP请求,通俗点讲,如何通过Java(模拟浏览器)发送HTTP请求. Java有原生的API可用于发送HTTP请求,即java.net.URL.java.net.UR ...

  8. JAVA发送HttpClient请求及接收请求结果

    1.写一个HttpRequestUtils工具类,包括post请求和get请求 ? 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 2 ...

  9. 第53节:Java当中的IO流(上)

    Java当中的IO流 在Java中,字符串string可以用来操作文本数据内容,字符串缓冲区是什么呢?其实就是个容器,也是用来存储很多的数据类型的字符串,基本数据类型包装类的出现可以用来解决字符串和基 ...

随机推荐

  1. 配置Windows Server 2008 允许多用户远程桌面连接

    开启远程桌面后,远程访问windows server 2008服务器时,默认只支持一个用户名同时只能创建一个远程连接,新建连接登录后会将前一个就踢掉,有没有办法像windows server 2005 ...

  2. Ajax--JavaScript实现

    Ajax:一种不用刷新整个页面便可与服务器通讯的办法 Ajax实现的步骤: 1.创建XMLHttpRequest对象 2.服务器向浏览器响应请求(注册监听) 3.浏览器与服务器建立连接 4.浏览器向服 ...

  3. THINK PHP U的用法

    public function index(){ //$db=new \Think\Model(); //$db=M('msg'); //$result=$db->query("sel ...

  4. 使用HTML5 API(AudioContext)实现可视化频谱效果

    如今的HTML5技术正让网页变得越来越强大,通过其Canvas标签与AudioContext对象可以轻松实现之前在Flash或Native App中才能实现的频谱指示器的功能. Demo: Cyand ...

  5. smarty练习:考试系统

    考试系统 (0607) 做一个类似于驾校考试的系统,可以选择要考试试题类型,选好后进入考试页面 使用的数据库表格:timu(题目)表,xuanxiang(选项)表,shiti(试题)表,shititi ...

  6. C++服务器linux开发环境管理

    在游戏服务器开发中,跨平台不是必须的.线上游戏既有windows下的C++..Net服务器也有linux下的C++.go.erlang服务器.但是无论如何都要保证开发环境和线上运行环境的一致,否则不同 ...

  7. c# 6.0 学习笔记

    refer : http://www.cnblogs.com/yinrq/p/5600530.html http://www.cnblogs.com/wolf-sun/p/5168217.html h ...

  8. assets文件夹资源的访问

    访问assets文件夹中的文件,分为以下几个步骤:1.在Activity里面调用getAssets(),获取AssetManager引用2.调用AssetManager.open(String fil ...

  9. JavaScript方法undefined/null原因探究及闭包简单实现

    昨天一个刚写前端不久的同学发消息问这个问题(如下图): HTML代码为(省略部分代码): <head> <script src="test.js">< ...

  10. Android中ListView异步加载数据

    1.主Activity public class MainActivity extends Activity { private ListView listView; private ArrayLis ...