我在这件事上疯了。我的curl命令有效:
卷曲
http://testuser:testpwd@qabox3:8501/xmlcontroller
但是,当我尝试在Java中看起来像一个等价的HTTP连接时,它给出了“连接拒绝”。我错过了什么?我今天尝试了十几种尝试建立这种联系的方式,但都没有想法。
URL url = new URL( "http://qabox3:8051/xmlcontroller" );
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
conn.setRequestMethod( "GET" );
String encoding = new sun.misc.BASE64Encoder().encode( "testuser:testpwd".getBytes() );
conn.setRequestProperty("Authorization", "Basic " + encoding );
InputStream content = conn.getInputStream(); // <--- fails here every time.
BufferedReader in = new BufferedReader( new InputStreamReader( content ) );
String line;
while ((line = in.readLine()) != null) {
System.out.println( line );
}
此外,我可以使用Java的运行时。执行()来执行CURL命令,它仍然有效……所以我显然在HTTURL连接中做了一些错误。
这里是我看到的栈(现在使用HTTPclipse,但基本上与Java LIBs相同的堆栈)。
Exception in thread "main" java.net.ConnectException: Connection refused: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
at java.net.Socket.connect(Socket.java:520)
at java.net.Socket.connect(Socket.java:470)
at java.net.Socket.<init>(Socket.java:367)
at java.net.Socket.<init>(Socket.java:240)
at org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory.createSocket(DefaultProtocolSocketFactory.java:80)
at org.apache.commons.httpclient.protocol.DefaultProtocolSocketFactory.createSocket(DefaultProtocolSocketFactory.java:122)
at org.apache.commons.httpclient.HttpConnection.open(HttpConnection.java:707)
at org.apache.commons.httpclient.HttpMethodDirector.executeWithRetry(HttpMethodDirector.java:387)
at org.apache.commons.httpclient.HttpMethodDirector.executeMethod(HttpMethodDirector.java:171)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:397)
at org.apache.commons.httpclient.HttpClient.executeMethod(HttpClient.java:323)
at MyClass.sendRequest(iQ411RequestHandlerProxy.java:277)
为了好玩,这里是curl详细输出。头上没什么特别的…
> GET /xmlcontroller HTTP/1.1
> Authorization: Basic cWFfc3VwZXI6cWFfc3VwZXI=
> User-Agent: curl/7.16.3 (i686-pc-cygwin) libcurl/7.16.3 OpenSSL/0.9.8k zlib/1.2.3 libssh2/0.15-CVS
> Host: qabox3:8501
> Accept: */*
>