用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可以用来操作文本数据内容,字符串缓冲区是什么呢?其实就是个容器,也是用来存储很多的数据类型的字符串,基本数据类型包装类的出现可以用来解决字符串和基 ...
随机推荐
- react-native-router-flux 下部导航
github url:https://github.com/aksonov/react-native-router-flux API: https://github.com/aksonov/react ...
- django初探
如果是自己建站耍的话,还是用Php方便,毕竟Php服务器便宜又到处都是. 但是python毕竟是一个新鲜的东西,特别是django,以前一直东python的语法,而且是我最早学习的语言之一,但是一直停 ...
- CSS 3层嵌套居中布局
<html> <head> <style type="text/css"> .root{ background-color: red; widt ...
- 一条带分页的sql
SELECT * FROM (SELECT USERID, TYPE, TYPE_DESC, SEX, USERNAME, HEADPORTRAIT, HOSPITAL, HLEVEL, DEPT, ...
- Top 100 words for advanced learners.
aberration (n.) something that differs from the norm (In 1974, Poland won the World Cup, but the suc ...
- microsoft
http://blog.csdn.net/morewindows/article/details/8684061 http://blog.csdn.net/watkinsong/article/det ...
- c++封装性
C++ code到运行程序 作为一个c++程序员这个应该是最应该知道的细节,简言之:编译----链接----可执行的程序.这里所说的细节主要是第一步的细节,编译器如何把c++代码编译成目标代码.概括的 ...
- iOS开发手记 - iOS9.3 UINavigationController添加后不显示storyboard中viewcontroller里的控件的解决方法
我原先是这么做的,通常也是这么做 - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSD ...
- 在什么情况下使用struct,struct与class的区别
Struct定义和使用 类是引用类型,是保存在托管堆中的.通过定义类,我们可以在数据的生存期上得到很高的灵活性,但是也会让程序的性能有一定的损失.虽然这种损失很小,但当我们只需要定义一个很小的结构时, ...
- java模拟http post
我们将使用java.net.URLConnection来完成一次post请求,假设要post数据到http://localhost:8080/doSome上: URLConnection urlCon ...