JSONP跨域

1.服务端
public class ServletTest extends HttpServlet {
public void init() throws ServletException {

}

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 获得客户端请求的方法
String method = request.getParameter("method");
if (method.equals("getInfo")) {
getXXXInfo(request, response);
}
}

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

}

public void getXXXInfo(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("id");
JSONObject json = new JSONObject();
// 得到结果集result拼成json
for(int i = 0; i < result.size(); i++){
HashMap hm = new HashMap();
// 把要用到的信息放到hm中
hm.put("title",result.get("title"));
...
json.put(new Integer(i), hm);
}

String output = json.toString();
response.setContentType("text/html;charset=GBK");
response.getWriter().print(output);
}
}


2.客户端
package com.bennett;

public class RemoteJson {
public static String url = Configuration.getProperty("sys.url");

public static ArrayList getXXXInfo(String id) throws IOException,
JSONException {
InputStream is = new URL(url + "/www/api/api.api?method=getInfo&id="
+ id).openStream();
try {
ArrayList al = new ArrayList();
BufferedReader rd = new BufferedReader(new InputStreamReader(is,
Charset.forName("GBK")));
String jsonText = readAll(rd);
JSONObject json = JSONObject.fromObject(jsonText);
for (int i = 0; i < json.size(); i++) {
JSONObject jsonrow = JSONObject.fromObject(json.get(String
.valueOf(i)));
HashMap hm = new HashMap();
hm.put("title", jsonrow.get("title"));
...
al.add(i, hm);
}
return al;
} finally {
is.close();
}
}

private static String readAll(Reader rd) throws IOException {
StringBuilder sb = new StringBuilder();
int cp;
while ((cp = rd.read()) != -1) {
sb.append((char) cp);
}
return sb.toString();
}

public static JSONObject readJsonFromUrl(String url) throws IOException,
JSONException {
InputStream is = new URL(url).openStream();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(is,
Charset.forName("UTF-8")));
String jsonText = readAll(rd);
JSONObject json = JSONObject.fromObject(jsonText);
return json;
} finally {
is.close();
}
}
}


3.web.xml
<servlet-mapping>
<servlet-name>ServletTest</servlet-name>
<url-pattern>/api/api.api</url-pattern>
</servlet-mapping>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值