用AjaxProxyServlet 跨域ajax请求

package org.xh.Servlet;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class AjaxProxyServlet
 */
public class AjaxProxyServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AjaxProxyServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html");
		response.setCharacterEncoding("utf-8");
        PrintWriter pw = response.getWriter();
        Enumeration paramNames = request.getParameterNames();
        StringBuffer bfParams = new StringBuffer();
        bfParams.append(request.getParameter("url")).append("?1=1");
        while(paramNames.hasMoreElements()) {
            String param = (String)paramNames.nextElement();
            if("url".equals(param)){continue;}
            bfParams.append("&").append(param).append("=").append(request.getParameter(param));
        }
        HttpURLConnection huc = null;
		try {
			// 取得连接
			huc = (HttpURLConnection) new URL(bfParams.toString())
					.openConnection();

			// 设置连接属性
			huc.setDoOutput(true);
			huc.setRequestMethod("POST");
			huc.setUseCaches(false);
			huc.setInstanceFollowRedirects(true);
			huc.setRequestProperty("Content-Type",
					"application/x-www-form-urlencoded");
			huc.setConnectTimeout(50000);
			huc.setReadTimeout(50000);
			huc.connect();

			// 参数
			// DataOutputStream out = new DataOutputStream(huc
			// .getOutputStream());
			// // The URL-encoded contend
			// // 正文,正文内容其实跟get的URL中'?'后的参数字符串一致
			// String content = "sheng_code=" + URLEncoder.encode("江苏", "utf-8");
			// // DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面
			// out.writeBytes(content);
			//
			// out.flush();
			// out.close(); // flush and close

			// 取得页面输出,并设置页面编码及缓存设置
			response.setContentType(huc.getContentType());
			response.setHeader("Cache-Control", huc.getHeaderField("Cache-Control"));
			response.setHeader("Pragma", huc.getHeaderField("Pragma"));
			response.setHeader("Expires", huc.getHeaderField("Expires"));

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					huc.getInputStream(), "utf-8"));
			String line;
			while ((line = reader.readLine()) != null) {
				pw.write(line);
			}
			reader.close();
		} catch (Exception e) {
			pw.write("outTime");
			e.printStackTrace();
		}finally{
			huc.disconnect();
			pw.flush();
			pw.close();
		}
	}
	
}

 

调用:

function getDq() {
	var str = jQuery("#name").val();
	$.ajax({  
        type : "post",  
        async:false,  
		data:{str : encodeURI(str),url:"访问地址"},
        url : "http://localhost:8080/m/AjaxProxyServlet",  
        success : function(data){  
        	if("outTime"!=data){
        		alert(data);
        	}else{
        		alert("网络连接超时!");
        	}
        },  
        error:function(){  
            alert('fail');  
        }  
    }); 
}

 

你可能感兴趣的:(java-tools)