java api接口提供_JAVA API接口提供注意事项

如果是API提供方,最好申明头部定义,方便调用方调用,否则会有跨域请求的问题。

ServletActionContext.getResponse().setHeader("Access-Control-Allow-Origin", "*");

如果是调用方,而提供方没有申明允许跨域请求。那有两种解决方案:

1、 采用Jquery 的 ajax方式 请求类型为jsonp 方式:

$.ajax({

type : "get", //jquey是不支持post方式跨域的

async:false,

data:{

cellphone: '13912345871',

real_name: 'jim',

password: pwd,

baby_dob: '2011-12-30',

access_token: key,

datasource: 'third'

},

url : 'http://www.xxx.com.cn/test.json', //跨域请求的URL

dataType : "jsonp",

//传递给请求处理程序,用以获得jsonp回调函数名的参数名(默认为:callback)

jsonp: "callback",

beforeSend :function(msg){

alert("正在查询您的绑定信息……");

},

//成功获取跨域服务器上的json数据后,会动态执行这个callback函数

success : function(msg){

//var jsonObj = eval(msg);

alert(msg);

}

});

2、 直接用JAVA 在action中执行URL得到返回值处理:

private String getBackJson(String url){

StringBuffer htmlBuffer = new StringBuffer();

String returnStr = null;

try {

InputStream inputSource = new URL(url).openStream();

int ch;

while ((ch = inputSource.read()) > -1) {

htmlBuffer.append((char) ch);

}

inputSource.close();

returnStr = new String(htmlBuffer);

returnStr = new String(returnStr.getBytes("ISO8859_1"),"UTF-8");

} catch (Exception e) {

System.out.println("get url result error!");

e.printStackTrace();

}

return returnStr;

}

分享到:

18e900b8666ce6f233d25ec02f95ee59.png

72dd548719f0ace4d5f9bca64e1d7715.png

2014-04-08 13:35

浏览 686

评论

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值