码迷,mamicode.com
首页 > Web开发 > 详细

用IO流发送Http请求

时间:2016-11-16 13:44:52      阅读:381      评论:0      收藏:0      [点我收藏+]

标签:个人信息   ram   for   nec   定义   http   密码   mode   span   

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请求

标签:个人信息   ram   for   nec   定义   http   密码   mode   span   

原文地址:http://www.cnblogs.com/wangchuanfu/p/6068958.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!