java web中开放接口并测试连接

1.java web 中的接口

/**
* 用户账号判断是否存在接口
* @param username 用戶名
* @return 已存在-1 不存在-0
*/
@RequestMapping("/userIsExitHttpInterface")
@ResponseBody

//@ResponseBody,不加这个注释,会接受不到json的返回值
public String userIsExitHttpInterface(HttpServletRequest request,HttpServletResponse response){
String username = request.getParameter("username");
YbbScUser user = scUserManager.findByProperty("account", username);
JSONObject jsonObject = new JSONObject(); //创建Json对象
if(user != null){
jsonObject.put("states", "1"); //设置Json对象的属性---1:已存在
}else{
jsonObject.put("states", "0"); //设置Json对象的属性---0:不存在
}
return jsonObject.toString();
}

 

2.调用开放的接口(测试类)

public class InterfaceTest {

public static void main(String[] args) {
Map<String, Object> mapParam = new HashMap<String, Object>();
JSONObject str = sendPost("http://localhost:8080/stms/user/scuser/userIsExitHttpInterface?username=ceshi");
System.out.println(str);
}

/**
* 向指定url发送POST请求
*
*/
public static JSONObject sendPost(String url) {
JSONObject jsonObj = null;
try {
URL realUrl = new URL(url);
URLConnection conn = realUrl.openConnection();
// 指定客户端能够接收的内容类型
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");// 设置连接的状态
// User-Agent的内容包含发出请求的用户信息
conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Charset", "UTF-8");
conn.setDoOutput(true);
conn.setDoInput(true);

PrintWriter out = new PrintWriter(conn.getOutputStream());
out.flush();
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
String str = "";
while ((line = in.readLine()) != null) {
str += line;
}
jsonObj = JSONObject.fromObject(str);
} catch (MalformedURLException e) {
System.err.println("URL协议、格式或者路径错误!" + e);
e.printStackTrace();
} catch (IOException e) {
System.err.println("URL连接失败!" + e);
e.printStackTrace();
} catch (Exception e) {
System.err.println("发送 POST 请求出现异常!" + e);
e.printStackTrace();
}
return jsonObj;
}
}

 

3.用工具测试

1.url和parameter,get提交

2.返回的json数据

 

4.测试ajax的跨域请求:

客户端:

//拼接需要的参数得到url
var url = EditPwdUrl + "?jsoncallback=?";
//ajax跨域请求水泥的修改密码的接口
$.getJSON(url, function(result) {
if (result.num == "1") {
$("#tf").submit();
} else if (result.num == "2") {
alertMsg.info("输入的旧密码错误!");
} else if (result.num == "0") {
alertMsg.info("修改密码失败!");
}
});

必须要有jsoncallback=?(原因不知道)

服务器端:

String jsoncallback = request.getParameter("jsoncallback");
String info = jsoncallback+"({\"num\":\"1\"})";
return info;

返回值中需要有jsoncallback(原因不知道)

 

更详细的跨域访问链接:

基于JQuery、Jsonp与Jersey的跨域访问    http://www.voidcn.com/article/p-cgngsmhk-o.html

 

posted @ 2018-11-07 14:25  wcxmn  阅读(1733)  评论(0编辑  收藏  举报