在 Bluemix 中从 Java 连接到安全网关

Connecting to a secure gateway from Java in Bluemix

我正在尝试从我的 Bluemix 帐户通过安全网关 (DataPower) 连接到 Web 服务器 (http/port:80)。我已经设置好所有内容,并且可以在我的仪表板中看到目的地等已启用。我正在使用 Java 连接到安全网关,但我一定遗漏了一些东西,因为我不断收到从网关客户端返回的 403。

我已添加:

connection.setRequestProperty("Authorization", "Bearer " + token);

但它仍然失败并显示 403。我假设我还需要提供网关 ID...但找不到任何文档或 Java 示例...

您可以通过创建一个像 www.google.com/80 这样的好网站(网页)的目的地来轻松做到这一点。我就是这么做的,然后在下面写了一些代码:

import java.io.*;
import java.net.*;
import javax.net.ssl.*;
import java.security.cert.X509Certificate;

public class test {
    /**
     * The main method.
     *
     * @param args - String[] - The command line arguments.
     */
    public static void main(String[] args) {

        String url = args[0];
//      String query = args[1];
//      String token = args[2];
        String charset = "UTF-8";

        BufferedReader br = null;

        try {
            // Create a trust manager that does not validate certificate chains
            TrustManager[] trustAllCerts = new TrustManager[] {new X509TrustManager() {
                    public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                        return null;
                    }
                    public void checkClientTrusted(X509Certificate[] certs, String authType) {
                    }
                    public void checkServerTrusted(X509Certificate[] certs, String authType) {
                    }
                }
            };

            // Install the all-trusting trust manager
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new java.security.SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

            // Create all-trusting host name verifier
            HostnameVerifier allHostsValid = new HostnameVerifier() {
                public boolean verify(String hostname, SSLSession session) {
                    return true;
                }
            };

            // Install the all-trusting host verifier
            HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

            URL _url = new URL(url);
//          URL _url = new URL(url + "?" + query);
            System.out.println("URL: " + _url);
//          HttpsURLConnection connection = (HttpsURLConnection)_url.openConnection();
            HttpURLConnection connection = (HttpURLConnection)_url.openConnection();
//          connection.setRequestMethod("GET");
//          connection.setRequestProperty("Authorization", "Bearer " + token);
            br = new BufferedReader(new InputStreamReader(connection.getInputStream()));

            System.out.println("****** Contents ********");            

            String input;

                while ((input = br.readLine()) != null){
                    System.out.println("MSG: " + input);
                }
                br.close();
        } catch (Exception e) {
            e.printStackTrace(System.err);
        }
    }
}

请注意,注释掉的内容适用于您可能想尝试的 HTTPS 连接(同样有效)。然后运行程序获取google网站首页的结果,如下图。

$ java -cp . test http://localhost:15017
URL: http://localhost:15017
****** Contents ********
MSG: <!doctype html><html itemscope="" itemtype="http://schema.org/WebPage" lang="en"><head><meta content="Search the world's information, including webpages, images, videos and more. Google has many special features to help you find exactly what you're looking for." name="description"><meta content="noodp" name="robots"><meta content="/images/google_favicon_128.png" itemprop="image"><title>Google</title><script>(function(){window.google={kEI:'EQ_AVZy-OIjz-AHlrYHgBA',kEXPI:'3700264,3700372,4029571,4029815,4031109,4032235,4032500,4032677,4033307,4033344,4033367,4034882,4036527,4036848,4037333,4037457,4037569,4038012,4038399,4039386,4039462,4039879,4039905,4039936,4040020,4040028,4040112,4040135,4040849,4040864,4040974,4040977,4040983,4041078,4041159,4041304,4041440,4041644,4041972,4042052,4042383,4042695,4042833,4042835,4043134,8300096,8300185,8300199,8300203,8300214,8500394,8501261,8501295,8501407,8501489,10200083,10201125,10201250,10201339',authuser:0,kscs:'c9c918f0_10'};google.kHL='en';})();(function(){google.lc=[];google.li=0;google.getEI=function(a){for(var b;a&&(!a.getAttribute||!(b=a.getAttribute("eid")));)a=a.parentNode;return b||google.kEI};google.getLEI=function(a){for(var b=null;a&&(!a.getAttribute||!(b=a.getAttribute("leid")));)a=a.parentNode;return b};google.https=function(){return"https:"==window.location.protocol};google.ml=function(){return null};google.time=function(){return(new Date).getTime()};google.log=function(a,b,d,e,g){a=google.logUrl(a,b,d,e,g);if(""!=a){b=new Image;var c=google.lc,f=google.li;c[f]=b;b.onerror=b.onload=b.onabort=function(){delete c[f]};window.google&&window.google.vel&&window.google.vel.lu&&window.google.vel.lu(a);b.src=a;google.li=f+1}};google.logUrl=function(a,b,d,e,g){var c="",f=google.ls||"";if(!d&&-1==b.search("&ei=")){var h=google.getEI(e),c="&ei="+h;-1==b.search("&lei=")&&((e=google.getLEI(e))?c+="&lei="+e:h!=google.kEI&&(c+="&lei="+google.kEI))}a=d||"/"+(g||"gen_204")+"?atyp=i&ct="+a+"&cad="+b+c+f+"&zx="+google.time();/^http:/i.test(a)&&google.https()&&(google.ml(Error("a"),!1,{src:a,glmm:1}),a="");return a};google.y={};google.x=function(a,b){google.y[a.id]=[a,b];return!1};google.load=function(a,b,d){google.x({id:a+k++},function(){google.load(a,b,d)})};var k=0;})();google.kCSI={};var _gjwl=location;function _gjuc(){var a=_gjwl.href.indexOf("#");if(0<=a&&(a=_gjwl.href.substring(a),0<a.indexOf("&q=")||0<=a.indexOf("#q="))&&(a=a.substring(1),-1==a.indexOf("#"))){for(var d=0;d<a.length;){var b=d;"&"==a.charAt(b)&&++b;var c=a.indexOf("&",b);-1==c&&(c=a.length);b=a.substring(b,c);if(0==b.indexOf("fp="))a=a.substring(0,d)+a.substring(c,a.length),c=d;else if("cad=h"==b)return 0;d=c}_gjwl.href="/search?"+a+"&cad=h";return 1}return 0}
MSG: function _gjh(){!_gjuc()&&window.google&&google.x&&google.x({id:"GJH"},function(){google.nav&&google.nav.gjh&&google.nav.gjh()})};window._gjh&&_gjh();</script><style>#gbar,#guser{font-size:13px;padding-top:1px !important;}#gbar{height:22px}#guser{padding-bottom:7px !important;text-align:right}.gbh,.gbd{border-top:1px solid #c9d7f1;font-size:1px}.gbh{height:0;position:absolute;top:24px;width:100%}@media all{.gb1{height:22px;margin-right:.5em;vertical-align:top}#gbar{float:left}}a.gb1,a.gb4{text-decoration:underline !important}a.gb1,a.gb4{color:#00c !important}.gbi .gb4{color:#dd8e27 !important}.gbf .gb4{color:#900 !important}
MSG: </style><style>body,td,a,p,.h{font-family:arial,sans-serif}body{margin:0;overflow-y:scroll}#gog{padding:3px 8px 0}td{line-height:.8em}.gac_m td{line-height:17px}form{margin-bottom:20px}.h{color:#36c}.q{color:#00c}.ts td{padding:0}.ts{border-collapse:collapse}em{font-weight:bold;font-style:normal}.lst{height:25px;width:496px}.gsfi,.lst{font:18px arial,sans-serif}.gsfs{font:17px arial,sans-serif}.ds{display:inline-box;display:inline-block;margin:3px 0 4px;margin-left:4px}input{font-family:inherit}a.gb1,a.gb2,a.gb3,a.gb4{color:#11c !important}body{background:#fff;color:black}a{color:#11c;text-decoration:none}a:hover,a:active{text-decoration:underline}.fl a{color:#36c}a:visited{color:#551a8b}a.gb1,a.gb4{text-decoration:underline}a.gb3:hover{text-decoration:none}#ghead a.gb2:hover{color:#fff !important}.sblc{padding-top:5px}.sblc a{display:block;margin:2px 0;margin-left:13px;font-size:11px}.lsbb{background:#eee;border:solid 1px;border-color:#ccc #999 #999 #ccc;height:30px}.lsbb{display:block}.ftl,#fll a{display:inline-block;margin:0 12px}.lsb{background:url(/images/srpr/nav_logo80.png) 0 -258px repeat-x;border:none;color:#000;cursor:pointer;height:30px;margin:0;outline:0;font:15px arial,sans-serif;vertical-align:top}.lsb:active{background:#ccc}.lst:focus{outline:none}</style><script></script></head><body bgcolor="#fff"><script>(function(){var src='/images/nav_logo199.png';var iesg=false;document.body.onload = function(){window.n && window.n();if (document.images){new Image().src=src;}
MSG: if (!iesg){document.f&&document.f.q.focus();document.gbqf&&document.gbqf.q.focus();}
MSG: }
MSG: })();</script><div id="mngb">    <div id=gbar><nobr><b class=gb1>Search</b> <a class=gb1 href="http://www.google.com/imghp?hl=en&tab=wi">Images</a> <a class=gb1 href="http://maps.google.com/maps?hl=en&tab=wl">Maps</a> <a class=gb1 href="https://play.google.com/?hl=en&tab=w8">Play</a> <a class=gb1 href="http://www.youtube.com/?tab=w1">YouTube</a> <a class=gb1 href="http://news.google.com/nwshp?hl=en&tab=wn">News</a> <a class=gb1 href="https://mail.google.com/mail/?tab=wm">Gmail</a> <a class=gb1 href="https://drive.google.com/?tab=wo">Drive</a> <a class=gb1 style="text-decoration:none" href="http://www.google.com/intl/en/options/"><u>More</u> &raquo;</a></nobr></div><div id=guser width=100%><nobr><span id=gbn class=gbi></span><span id=gbf class=gbf></span><span id=gbe></span><a href="http://www.google.com/history/optout?hl=en" class=gb4>Web History</a> | <a  href="/preferences?hl=en" class=gb4>Settings</a> | <a target=_top id=gb_70 href="https://accounts.google.com/ServiceLogin?hl=en&continue=http://www.google.com/" class=gb4>Sign in</a></nobr></div><div class=gbh style=left:0></div><div class=gbh style=right:0></div>    </div><center><br clear="all" id="lgpd"><div id="lga"><img alt="Google" height="95" src="/images/srpr/logo9w.png" style="padding:28px 0 14px" width="269" id="hplogo" onload="window.lol&&lol()"><br><br></div><form action="/search" name="f"><table cellpadding="0" cellspacing="0"><tr valign="top"><td width="25%">&nbsp;</td><td align="center" nowrap=""><input name="ie" value="ISO-8859-1" type="hidden"><input value="en" name="hl" type="hidden"><input name="source" type="hidden" value="hp"><input name="biw" type="hidden"><input name="bih" type="hidden"><div class="ds" style="height:32px;margin:4px 0"><input style="color:#000;margin:0;padding:5px 8px 0 6px;vertical-align:top" autocomplete="off" class="lst" value="" title="Google Search" maxlength="2048" name="q" size="57"></div><br style="line-height:0"><span class="ds"><span class="lsbb"><input class="lsb" value="Google Search" name="btnG" type="submit"></span></span><span class="ds"><span class="lsbb"><input class="lsb" value="I'm Feeling Lucky" name="btnI" onclick="if(this.form.q.value)this.checked=1; else top.location='/doodles/'" type="submit"></span></span></td><td class="fl sblc" align="left" nowrap="" width="25%"><a href="/advanced_search?hl=en&amp;authuser=0">Advanced search</a><a href="/language_tools?hl=en&amp;authuser=0">Language tools</a></td></tr></table><input id="gbv" name="gbv" type="hidden" value="1"></form><div id="gac_scont"></div><div style="font-size:83%;min-height:3.5em"><br><div id="prm"><font id="hpplink" size="-1" style="behavior:url(#default#userdata);display:none"><span style="color:red"></span><a href="https://www.youtube.com/watch?v=06olHmcJjS0&amp;utm_medium=HPPMobileEN&amp;utm_campaign=Translate" onclick="google.promos&&google.promos.link&& google.promos.link.cl()">Google Translate meets La Bamba</a></font><br><br><br><script type="text/javascript">(function(){var e={ACCEPT:"a",LIMITED_ACCEPT:"l",CANCEL:"c",DISMISS:"d",CLICK:"h",IMPRESSION:"i",NO_THANKS:"n",X_BUTTON:"x",MGMHP_ACCEPT:"ma",MGMHP_CANCEL:"mc",MGMHP_IMPRESSION:"mi",MGMHPPD_ACCEPT:"pa",MGMHPPD_CANCEL:"pc",MGMHPPD_IMPRESSION:"pi",MGMHPPD_NO_THANKS:"pn",MGMHPPD_NO_BUTTON:"px",MGMHPPD_DISMISS:"pd",PUSHDOWN_ACCEPT:"gpa",PUSHDOWN_IMPRESSION:"gpi",PUSHDOWN_NO_THANKS:"gpn",PUSHDOWN_X_BUTTON:"gpx",PUSHDOWN_DISMISS:"gpd"};var f,g,h=0,k;google.promos=google.promos||{};google.promos.link=google.promos.link||{};google.promos.link.getExtraLogData_=function(b){var a=document.getElementById(k);if(a){var c=g+"_upccb",d=parseInt(window.gbar.up.gpd(a,c)||0,10);d++;h++;window.gbar.up.spd(a,c,d);a=[["upcc",h].join("="),["upccb",d].join("=")];b&&a.push(b);return a.join("&")}return""};google.promos.link.cl=function(b){try{window.gbar.up.sl(g,f,e.CLICK,google.promos.link.getExtraLogData_(b),1)}catch(a){google.ml(a,!1,{cause:f+"_CL"})}};function l(){var b=["gpd","spd","sl"];if(!window.gbar||!window.gbar.up)return!1;for(var a=0,c;c=b[a];a++)if(!(c in window.gbar.up))return!1;return!0}google.promos.link.init=function(b,a,c){try{if(l()){g=b;f=a;k=c;var d=document.getElementById(k);d&&(d.style.display="",window.gbar.up.sl(g,f,e.IMPRESSION))}else google.ml(Error("apa"),!1,{cause:a+"_INIT"})}catch(m){google.ml(m,!1,{cause:f+"_INIT"})}};})();</script><script>(function(){var sourceWebappPromoID=5080838;var payloadType=3;window.gbar&&gbar.up&&gbar.up.r&&gbar.up.r(payloadType,function(show){if (show){google.promos.link.init(sourceWebappPromoID,payloadType,'hpplink');}
MSG: });})();</script></div></div><span id="footer"><div style="font-size:10pt"><div style="margin:19px auto;text-align:center" id="fll"><a href="/intl/en/ads/">Advertising&nbsp;Programs</a><a href="/services/">Business Solutions</a><a href="https://plus.google.com/116899029375914044550" rel="publisher">+Google</a><a href="/intl/en/about.html">About Google</a></div></div><p style="color:#767676;font-size:8pt">&copy; 2015 - <a href="/intl/en/policies/privacy/">Privacy</a> - <a href="/intl/en/policies/terms/">Terms</a></p></span></center><script>(function(){window.google.cdo={height:0,width:0};(function(){var a=window.innerWidth,b=window.innerHeight;if(!a||!b)var c=window.document,d="CSS1Compat"==c.compatMode?c.documentElement:c.body,a=d.clientWidth,b=d.clientHeight;a&&b&&(a!=google.cdo.width||b!=google.cdo.height)&&google.log("","","/client_204?&atyp=i&biw="+a+"&bih="+b+"&ei="+google.kEI);})();})();</script><div id="xjsd"></div><div id="xjsi" data-jiis="bp"><script>(function(){function c(b){window.setTimeout(function(){var a=document.createElement("script");a.src=b;document.getElementById("xjsd").appendChild(a)},0)}google.dljp=function(b,a){google.xjsu=b;c(a)};google.dlj=c;})();(function(){window.google.xjsrm=[];})();if(google.y)google.y.first=[];if(!google.xjs){window._=window._||{};window._._DumpException=function(e){throw e};if(google.timers&&google.timers.load.t){google.timers.load.t.xjsls=new Date().getTime();}google.dljp('/xjs/_/js/k\x3dxjs.hp.en_US.qQVQbzN3If0.O/m\x3dsb_he,d/rt\x3dj/d\x3d1/t\x3dzcms/rs\x3dACT90oEYlcPV9fDT1NHvaau1us2MvYxYhg','/xjs/_/js/k\x3dxjs.hp.en_US.qQVQbzN3If0.O/m\x3dsb_he,d/rt\x3dj/d\x3d1/t\x3dzcms/rs\x3dACT90oEYlcPV9fDT1NHvaau1us2MvYxYhg');google.xjs=1;}google.pmc={"sb_he":{"agen":true,"cgen":true,"client":"heirloom-hp","dh":true,"ds":"","fl":true,"host":"google.com","jam":0,"jsonp":true,"msgs":{"cibl":"Clear Search","dym":"Did you mean:","lcky":"I\u0026#39;m Feeling Lucky","lml":"Learn more","oskt":"Input tools","psrc":"This search was removed from your \u003Ca href=\"/history\"\u003EWeb History\u003C/a\u003E","psrl":"Remove","sbit":"Search by image","srch":"Google Search"},"ovr":{},"pq":"","refoq":true,"refpd":true,"rfs":[],"scd":10,"sce":5,"stok":"HqaK0mXTN7fM6g-2k2REZgJuoXg"},"d":{}};google.y.first.push(function(){if(google.med){google.med('init');google.initHistory();google.med('history');}});if(google.j&&google.j.en&&google.j.xi){window.setTimeout(google.j.xi,0);}
MSG: </script></div></body></html>