我已经实现了一个 servlet 并将其部署在 Jboss 4.0.3 的 war 文件夹中,以连接到外部网站。我的机器在代理后面,我也有有效的代理身份验证凭据。
当我尝试在程序中不提供任何代理设置的情况下进行连接时,我得到:
Servlet SearchRequestHandler 的 Servlet.service() 引发异常 java.io.IOException:服务器返回 HTTP 响应代码:500 用于 URL: http: //www.sample.com/test.do
如果我只使用代理服务器和代理端口:
System.setProperty("java.net.useSystemProxies","false");
System.setProperty("http.proxyHost", "192.168.1.226");
System.setProperty("http.proxyPort", "3128");
或者
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("192.168.1.226", 3128));
URL _serverConnection = new URL("http://www.sample.com/test.do");
HttpURLConnection _connection = (HttpURLConnection) _serverConnection.openConnection(proxy);
我收到需要身份验证的错误:
Servlet SearchRequestHandler 的 Servlet.service() 引发异常 java.io.IOException:服务器返回 HTTP 响应代码:407 对于 URL: http: //www.sample.com/test.do
如果我将身份验证标头添加到请求中,例如:
String encoded = new String(Base64Encoder.encode(new String("shantha:******").getBytes()));
_connection.setRequestProperty("Proxy-Authorization", "Basic " + encoded);
或者
Authenticator.setDefault(new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return (new PasswordAuthentication("shantha",
"******".toCharArray()));
}
});
我还是一样:
Servlet SearchRequestHandler 的 Servlet.service() 引发异常 java.io.IOException:服务器返回 HTTP 响应代码:500 用于 URL: http: //www.sample.com/test.do
.
上面提到的没有代理设置的基本程序是:
URL _serverConnection = new URL("http://www.sample.com/test.do");
HttpURLConnection _connection = null;
StringBuffer _strBuffer = new StringBuffer();
_connection = (HttpURLConnection) _serverConnection.openConnection();
_connection.setUseCaches(false);
_connection.setDoOutput(true);
_connection.setDoInput(true);
_connection.setRequestMethod("POST");
OutputStream _outStream = _connection.getOutputStream ();
BufferedWriter _bufWriter = new BufferedWriter( new OutputStreamWriter(_outStream, "UTF-8"));
_bufWriter.write("search-param-string");
_bufWriter.flush();
_bufWriter.close();
_outStream.close ();
int _status = _connection.getResponseCode();
BufferedReader _bufReader = new BufferedReader(new InputStreamReader(_connection.getInputStream()));
String _outputLine;
while ((_outputLine = _bufReader.readLine()) != null) {
_strBuffer.append(_outputLine + "\n");
}
我也尝试过代理选择器,但它不起作用并给出相同的 500 错误。如果我在具有 main 方法的独立类中运行程序,它可以与代理设置一起使用。
如果有人可以帮助解决这个问题,我真的很感激。