用IO流發送Http請求

來源:互聯網
上載者:User

標籤:個人資訊   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請求

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.