在后台模拟页面发出请求并获取结果

package com.uniestate.action;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class BaseAction extends ActionSupport {

    protected Map session;
    /**
     * 连接超时
     */
    private int connectTimeOut = 5000;

    /**
     * 读取数据超时
     */
    private int readTimeOut = 10000;

    /**
     * 请求编码
     */
    private String requestEncoding = "UTF-8";

    /* 杩斿洖JSON */
    protected void ReturnMessage(String msg) {
        HttpServletResponse response = ServletActionContext.getResponse();
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
            writer.print(msg);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        writer.flush();
        writer.close();
    }

    protected  String GetData(String urlStr) {
        BufferedReader l_reader = null;
        String sTotalString="";
        try {
            URL url = new URL(urlStr);
            URLConnection connection = url.openConnection();
            String sCurrentLine;
            sCurrentLine = "";
            sTotalString = "";
            InputStream l_urlStream;
            l_urlStream = connection.getInputStream();
            l_reader = new BufferedReader(new InputStreamReader(l_urlStream, "UTF-8"));
            while ((sCurrentLine = l_reader.readLine()) != null) {
                sTotalString += sCurrentLine;
            }
            //return sTotalString;
        } catch (Exception ex) {
            ex.printStackTrace();
            return "FAILD:" + ex.getMessage();
        } finally {
            try {
                if (l_reader != null) {
                    l_reader.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
                return "FAILD:" + ex.getMessage();
            }
        }
        return sTotalString;
    }

    /* 转向 */
    protected String doPost(String inReqUrl) {
        String reqUrl = inReqUrl;
        Map parameters = this.getParameterMap();
        HttpURLConnection url_con = null;
        String responseContent = null;
        try {
            StringBuffer params = new StringBuffer();
            for (Iterator iter = parameters.entrySet().iterator(); iter.hasNext();) {
                Entry element = (Entry) iter.next();
                params.append(element.getKey().toString());
                params.append("=");
                params.append(URLEncoder.encode(element.getValue().toString(), requestEncoding));
                params.append("&");
            }

            if (params.length() > 0) {
                params = params.deleteCharAt(params.length() - 1);
            }

            URL url = new URL(reqUrl);
            url_con = (HttpURLConnection) url.openConnection();
            url_con.setRequestMethod("POST");
            System.setProperty("sun.net.client.defaultConnectTimeout", String.valueOf(connectTimeOut));// (单位:毫秒)jdk1.4换成这个,连接超时
            System.setProperty("sun.net.client.defaultReadTimeout", String.valueOf(readTimeOut)); // (单位:毫秒)jdk1.4换成这个,读操作超时
            // url_con.setConnectTimeout(5000);//(单位:毫秒)jdk
            // 1.5换成这个,连接超时
            // url_con.setReadTimeout(5000);//(单位:毫秒)jdk 1.5换成这个,读操作超时
            url_con.setDoOutput(true);
            byte[] b = params.toString().getBytes();
            url_con.getOutputStream().write(b, 0, b.length);
            url_con.getOutputStream().flush();
            url_con.getOutputStream().close();

            InputStream in = url_con.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(in, requestEncoding));
            String tempLine = rd.readLine();
            StringBuffer tempStr = new StringBuffer();
            // String crlf=System.getProperty("line.separator");
            while (tempLine != null) {
                tempStr.append(tempLine);
                // tempStr.append(crlf);
                tempLine = rd.readLine();
            }
            responseContent = tempStr.toString();
            rd.close();
            in.close();
        } catch (IOException e) {
            responseContent = "ERROR";
        } finally {
            if (url_con != null) {
                url_con.disconnect();
            }
        }
        return responseContent;
    }

    /* 杞寲涓烘暟瀛 */
    protected int ConvertObjToInt(String value) {
        try {
            return Integer.parseInt(value);

        } catch (Exception ex) {
            return 0;
        }

    }

    /* 获取网页参数 */
    protected Map getParameterMap() {
        HttpServletRequest request = ServletActionContext.getRequest();
        // 参数Map
        Map properties = request.getParameterMap();
        // 返回值Map
        Map returnMap = new HashMap();
        Iterator entries = properties.entrySet().iterator();
        Map.Entry entry;
        String name = "";
        String value = "";
        while (entries.hasNext()) {
            entry = (Map.Entry) entries.next();
            name = (String) entry.getKey();
            Object valueObj = entry.getValue();
            if (null == valueObj) {
                value = "";
            } else if (valueObj instanceof String[]) {
                String[] values = (String[]) valueObj;
                for (int i = 0; i < values.length; i++) {
                    value = values[i] + ",";
                }
                value = value.substring(0, value.length() - 1);
            } else {
                value = valueObj.toString();
            }
            returnMap.put(name, value);
        }
        return returnMap;
    }

    /* 获取参数 */
    protected String GetParam(String keyValue) {
        HttpServletRequest request = ServletActionContext.getRequest();
        try {
            String nameStr = request.getParameter(keyValue);
            nameStr = new String(java.net.URLDecoder.decode(nameStr, "UTF-8"));
            return nameStr;
        } catch (Exception ex) {
            return request.getParameter(keyValue);
        }
    }

}

被请求的url的方法最后需按照以下格式,数据才能被接收

HttpServletResponse response = ServletActionContext.getResponse();
            response.setCharacterEncoding("utf-8");
            PrintWriter writer = response.getWriter();
            writer.print(json);
            writer.flush();
            writer.close();

你可能感兴趣的:(在后台模拟页面发出请求并获取结果)