java后台跨域请求
- maven引入依赖
<!--跨域问题-->
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
后台跨域
- 以微信登录接口为例。 前端使用ajax传需要值到后台,baseModel是自定义的返回工具类,根据需要自定义返回data和msg。
/**
* 微信登录接口
* @param appid
* @param secret
* @param js_code
* @param grant_type
* @param baseModel
* @param request
* @return
* @throws Exception
*/
@RequestMapping("/appLogin")
@ResponseBody
public BaseModel getDAGLInfo(String appid,String secret,String js_code,String grant_type,BaseModel baseModel,HttpServletRequest request) throws Exception{
HttpClient client = new HttpClient();
String url ="https://api.weixin.qq.com/sns/jscode2session";
PostMethod method = new PostMethod(url);
client.getParams().setContentCharset("UTF-8");
method.setRequestHeader("ContentType",
"application/x-www-form-urlencoded;charset=UTF-8");
try {
//Long time = System.currentTimeMillis() / 1000L;
NameValuePair[] data = {
new NameValuePair("appid", appid),
new NameValuePair("secret", secret),
new NameValuePair("js_code", js_code),
new NameValuePair("grant_type", grant_type),
};
method.setRequestBody(data);
client.executeMethod(method);
String submitResult = method.getResponseBodyAsString();
baseModel.setData(JSONObject.parse(submitResult));
return baseModel;
}catch(Exception e){
e.printStackTrace();
baseModel.setMessage("数据接口请求异常,请联系管理员!");
return baseModel;
}
}
}