用IO流发送Http请求
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请求的更多相关文章
- 通过http流发送post请求
一般都是用curl扩展来完成,看了手册的通过stream的方式更加简单. 请求脚本stream.php $url = 'http://localhost/stream_api.php'; $body ...
- 非阻塞IO发送http请求
import socket from urllib.parse import urlparse from selectors import DefaultSelector, EVENT_READ, E ...
- Java发送socket请求的工具
package com.tech.jin.util; import java.io.ByteArrayOutputStream; import java.io.IOException; import ...
- 如何在WinForm中发送HTTP请求
如何在WinForm中请求发送HTTP 手工发送HTTP请求主要是调用 System.Net的HttpWebResponse方法 手工发送HTTP的GET请 求: string strURL = &q ...
- Java基础知识强化之IO流笔记71:NIO之 NIO的(New IO流)介绍
1. I/O 简介 I/O ( 输入/输出 ):指的是计算机与外部世界或者一个程序与计算机的其余部分的之间的接口.它对于任何计算机系统都非常关键,因而所有 I/O 的主体实际上是内置在操作系统中的. ...
- C#后台发送HTTP请求
using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using Syst ...
- 通过java.net.URLConnection发送HTTP请求的方法
一.前言 如何通过Java发送HTTP请求,通俗点讲,如何通过Java(模拟浏览器)发送HTTP请求. Java有原生的API可用于发送HTTP请求,即java.net.URL.java.net.UR ...
- 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 ...
- 第53节:Java当中的IO流(上)
Java当中的IO流 在Java中,字符串string可以用来操作文本数据内容,字符串缓冲区是什么呢?其实就是个容器,也是用来存储很多的数据类型的字符串,基本数据类型包装类的出现可以用来解决字符串和基 ...
随机推荐
- Git简明教程
http://www.jianshu.com/p/16ad0722e4cc http://www.jianshu.com/p/f7ec8310ccd2
- JavaScript 之 使用 XMLHttpRequest 预览文件(图片)
<div id="div1"> <input type="file" id="uploadfile" style=&quo ...
- 利用 Makefile 写的小程序
1.建立一个工程 2.写一个进度条的程序(原理就是在同一位置重复打印某一个字符(变化),达到动态显示的效果) 所以说我们这里只用回车'\r',覆盖这一行以前的输出,重新向缓冲区写数据刷新缓冲区,就能达 ...
- noip201506 Message 信息传递
试题描述: 有 n 个同学(编号为 1 到 n )正在玩一个信息传递的游戏.在游戏里每人都有一个固定的信息传递对象,其中,编号为 i 的同学的信息传递对象是编号为 T_i 的同学.游戏开始时,每人都只 ...
- Android Fragment用法之给Activity创建事件回调
在某些案例中,可能需要Fragment与Activity共享事件.在Fragment内部定义一个回调接口是一个好方法,并且规定由持有它的Activity实现这个回调方法.当Activity通过接口接受 ...
- 基于jquery的页面预载入效果(loading)
css代码: <style> #loading{ position:absolute; width:300px; top:0px; left:50%; margin-left:-150px ...
- Js打开网页后居中显示
使用JavaScript定义打开网页后居中显示,并可为窗口设置大小,使用“window.open”方法打开新窗口:先来看完整的代码及调用方法: <html xmlns="http:// ...
- Visual Studio调试之避免单步跟踪调试模式
Visual Studio调试之避免单步跟踪调试模式 写完Visual Studio调试之断点进阶篇之后,想分享一下我常用的一些调试技巧,后面发现写之前,一些背景知识需要介绍一下. 下面是几篇今年2月 ...
- Linux_ERROR 1045 (28000): Access denied for user 'root'@'localhost'
MySQL生成了root用户的随机密码(如下截图所示),并将这个随机密码放置在/root/.mysql_secret中.并且强制在第一次登陆时修改root用户的密码.Mysql 5.6及以后版本出处于 ...
- uva 10026 Problem C: Edit Step Ladders
http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&p ...