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