gpt4 book ai didi

Java HttpConnection 被拒绝,但 curl 等效工作

转载 作者:可可西里 更新时间:2023-11-01 16:02:35 28 4
gpt4 key购买 nike

我对这个失去了理智。我的 curl 命令有效:

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 的 Runtime.exec() 来执行 curl 命令并且它仍然有效...所以我显然在 HttpURLConnection 中做错了什么。

这是我看到的堆栈(现在使用 HttpClient,但与 Java 库基本相同的堆栈)。

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: */*
>

最佳答案

您似乎使用了两个不同的端口号:8501 和 8051?这可能是问题所在,还是发布问题时出现错字?

curl http://testuser:testpwd@qabox3:8501/xmlcontroller

URL url = new URL( "http://qabox3:8051/xmlcontroller" );

问候,伊恩

关于Java HttpConnection 被拒绝,但 curl 等效工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1241092/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com