假如您需要通过js跨域向https发起请求,方法如下两种:

来源:互联网 发布:linux黑客大曝光 编辑:程序博客网 时间:2024/05/16 00:49

假如您需要通过js跨域向https发起请求,方法如下两种:

第一种:$.getJSON 后面的url中需要加上?callback=?

注意:被访问的https服务器端必须要返回json数据。

如果您服务器不能改动,只能我们在客户端想办法的话,用下面第二种方法吧


第二种:

private static class TrustAnyTrustManager implements X509TrustManager {

   public void checkClientTrusted(X509Certificate[] chain, String authType)
     throws CertificateException {
   }

   public void checkServerTrusted(X509Certificate[] chain, String authType)
     throws CertificateException {
   }

   public X509Certificate[] getAcceptedIssuers() {
    return new X509Certificate[] {};
   }
}

@SuppressWarnings("deprecation")
private static class TrustAnyHostnameVerifier implements com.sun.net.ssl.HostnameVerifier {
@Override
public boolean verify(String arg0, String arg1) {
      return true;
}
}


public void activeI2000KeepLive(){
   InputStream is = null;
   PrintWriter pw = null;
   try {
    SSLContext sc = SSLContext.getInstance("SSL");
    sc.init(null, new TrustManager[] { new TrustAnyTrustManager() },
      new java.security.SecureRandom());
    String remoteUrl = InitAction.REMOTE_URL;
    final String url = remoteUrl.substring(0,remoteUrl.indexOf("/", 8)) + "/servlet/keeplive";
    URL console = new URL(url);
//    javax.net.ssl.HttpsURLConnection conn =  (HttpsURLConnection) console.openConnection();
    com.sun.net.ssl.internal.www.protocol.https.HttpsURLConnectionOldImpl conn =  (HttpsURLConnectionOldImpl) console.openConnection();
    conn.setSSLSocketFactory(sc.getSocketFactory());
    conn.setHostnameVerifier(new TrustAnyHostnameVerifier());
    conn.connect();
    is = conn.getInputStream();
    DataInputStream indata = new DataInputStream(is);
    String ret = "";
    String str_return = "";
    while (ret != null) {
     ret = indata.readLine();
     if (ret != null && !ret.trim().equals("")) {
      str_return = str_return
        + new String(ret.getBytes("ISO-8859-1"), "GBK");
     }
    }
    System.out.println(str_return);
    
    pw = ServletActionContext.getResponse().getWriter();
    if(is != null){
        pw.write("success");
    }else{
        pw.write("error");
    }
    
    conn.disconnect();
   } catch (ConnectException e) {
       
   }catch (Exception e) {
       
   }
   finally {
     try {
         if(is != null){
             is.close();
         }
         if(pw != null){
             pw.close();
         }
    } catch (IOException e) {
    }
   }
}