web几种跨域請求的方式

来源:互联网 发布:手机淘宝设置降价提醒 编辑:程序博客网 时间:2024/06/07 17:23
Ajax跨域請求
//請求的路徑和携帶的參數
var xhrurl = “http://ip:端口號/項目名/請求地址(或者jsp頁面)?參數(cu=kefu1)”;
  $.ajax({
          type : "get",//请求方式
          async : false,//是否异步
          //注意:async: false,(默认是true);
          //如上:false为同步,这个方法中的Ajax请求将整个浏览器锁死,
          //只有tet.php执行结束后,才可以执行其它操作。
          //当async: true 时,ajax请求是异步的。但是其中有个问题:这个放过中的ajax请求和其后面的操作是异步执行的,
          //那么当tet.php还未执行完,就可能已经执行了 ajax请求后面的操作,
          //如: alert(temp+'   end');
          //然而,temp这个数据是在ajax请求success后才赋值的,结果,输出时会为空。

          url :xhrurl,
          cache : false,
          dataType : "jsonp",  //跨域json请求一定是jsonp
          jsonp: "callbackparam",  //跨域请求的参数名,默认是callback
          jsonpCallback:"jsonpCallback1",
          data:{"query":"civilnews"},    //请求参数(如果url带了参数,就没必要)
     beforeSend: function() {
        //请求前的处理
        },
     success: function(data) {
         //请求成功处理,和本地回调完全一样
     },
     complete: function() {
        //请求完成的处理
     },
     error: function() {
        //请求出错处理
      }
     });
注意: jsonp: "callbackparam"
       jsonpCallback:"jsonpCallback1"
这两个参数最终会拼接在请求的url后面,变成 http://www.xxx.com/ajax/xxx.jsp?callbackparam=jsonCallback1
服务端要获取这个参数值:"jsonCallback1"  ,拼接在要输出的JSON数据最前面,不然就算请求成功你也只会看到警告:

java(安全跨域)java.net.url技术
//导入的类
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;
import java.util.Random;
//测试方法
public class Test {
    //(测试)主方法
    public static void main(String[] args) throws Exception {
        //url
        String url="";
        //时间戳
        String timesTamp=getCurrentTimestamp()+"";
        //8位随机字符串
        String  str=genRandomNum();
        //地方编号
        String wherebh="";
        //第三方key
        String key="";
        //手机号码
        String phone="";
        //测试信息
        String msg="系统接口测试";
        //sign值
        String string="{'phone':'"+phone+"','msg':'"+msg+"','Wherebh':'"+wherebh+"','str':'"+str+"','Timestamp':'"+timesTamp+"','Sign':''}";
        System.out.println("content值:" +string);
        //获得签名
        String sign=GetSign(string,key);
        //待发送报文
        String str="{'phone':'"+phone+"','msg':'"+msg+"','Wherebh':'"+wherebh+"','str':'"+str+"','Timestamp':'" +timesTamp+"','Sign':'"+sign+"'}";
        System.out.println("发送报文:" +str);
        //httpHttpClient客户端post请求
        String responseContent = HttpClientUtil.getInstance().sendHttpPost(url,str);
        System.out.println("返回报文:" + responseContent);
    }
    //java方法(安全跨域)java.net.url实现后台发出http请求并输出获取到的数据
    public static String sendPost(String url, String encode) {//请求路径和发生的报文
        URL localURL = null;
        HttpURLConnection localHttpURLConnection = null;
        BufferedReader localBufferedReader = null;
        String result = "";
        try {
                localURL = new URL(url);
                localHttpURLConnection = (HttpURLConnection) localURL.openConnection();
                localHttpURLConnection.setDoOutput(true);
                localHttpURLConnection.setDoInput(true);
                localHttpURLConnection.setConnectTimeout(200* 100);
                localHttpURLConnection.setUseCaches(false);
                localHttpURLConnection.setRequestProperty("Content-Type", "application/json;charset=utf-8");//json数据传输
                localHttpURLConnection.setRequestMethod("POST");//提交方式
                localHttpURLConnection.connect();
                OutputStreamWriter localObject1 = new OutputStreamWriter(localHttpURLConnection.getOutputStream(), "utf-8");//传输编码格式
                localObject1.write(encode);
                localObject1.flush();
                localObject1.close();
                localBufferedReader = new BufferedReader(new InputStreamReader(localHttpURLConnection.getInputStream(), "utf-8"));
                String str1;
                while ((str1 = localBufferedReader.readLine()) != null) {
                    result = new StringBuilder().append(str1).toString();
                }
                result = result.trim();
            } catch (Exception localException) {
               }
        return result;
            }
    /**
     * 生成 MD5
     * @param data 待处理数据
     * @return MD5结果
     */
    public static String GetSign(String content, String key) throws Exception {
        content += "&key=" + key;
        java.security.MessageDigest md = MessageDigest.getInstance("MD5");
        byte[] array = md.digest(content.getBytes("UTF-8"));
        StringBuilder sb = new StringBuilder();
        for (byte item : array) {
            sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
        }
        return sb.toString().toUpperCase();
    }
    /**
     * 获取当前时间戳,单位秒
     * @return
     */
    public static long getCurrentTimestamp() {
        return System.currentTimeMillis()/1000;
    }
    /**8位随机字符串
     *
     * @return
     */
    public static String genRandomNum(){  
        int  maxNum = 36;  
        int i;  
        int count = 0;  
        char[] str = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',  
          'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',  
          'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };      
        StringBuffer pwd = new StringBuffer("");  
        Random r = new Random();  
        while(count < 8){  
         i = Math.abs(r.nextInt(maxNum));     
         if (i >= 0 && i < str.length) {  
          pwd.append(str[i]);  
          count ++;  
         }  
        }  
        return pwd.toString();  
      }  
}

原创粉丝点击