Ajax跨域获取远程的json数组,通过servlet中转一下,servlet可以这样写:
之前用的是get方式,但是,json数组太长,通过流的方式数据没有取完就返回给servlet,所以改用下面的方法:(有效)
public void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
boolean requestType = true;
resp.setContentType("text/html;charset=utf-8");
PrintWriter out = resp.getWriter();
String wapHost=PropertyManager.getProperty("wap.mobile.host");
String msource=wapHost+"productdetail.do";
String page=req.getParameter("page");
String pid=req.getParameter("id");
msource=msource+"?pid="+pid+"&page="+page;
String url=msource;
HttpClient client = new HttpClient();
HttpMethod method = null;
if(requestType){//判断请求方式,并实例化HttpMethod对象,true:POST,false:GET
method = new UTF8PostMethod(url);
}else{
method = new GetMethod(url);
}
client.executeMethod(method);//执行请求
String bodystr = method.getResponseBodyAsString();//返回结果
out.println(bodystr);//将结果返回给客户端
}
/**
* 内部类,转换URL字符串为UTF-8
* @author Administrator
*
*/
private static class UTF8PostMethod extends PostMethod {
public UTF8PostMethod(String url) {
super(url);
}
@Override
public String getRequestCharSet() {
return "UTF-8";
}
}