我想将具有基本身份验证(用户名,密码)的代理用于Java中的连接(并且仅此连接)。以下代码适用于HTTP URL(例如“
http://www.google.com ”):
URL url = new URL("http://www.google.com");
HttpURLConnection httpURLConnection = null;
InetSocketAddress proxyLocation = new InetSocketAddress(proxyHost, proxyPort);
Proxy proxy = new Proxy(Proxy.Type.HTTP, proxyLocation);
httpURLConnection = (HttpURLConnection) url.openConnection(proxy);
// Works for HTTP only! Doesn't work for HTTPS!
String encoded = new sun.misc.BASE64Encoder().encodeBuffer((proxyUserName + ":" + proxyPassword).getBytes()).replace("\r\n", "");
httpURLConnection.setRequestProperty("Proxy-Authorization", "Basic " + encoded);
InputStream is = httpURLConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int data = isr.read();
while(data != -1){
char c = (char) data;
data = isr.read();
System.out.print(c);
}
isr.close();
但是,该代码不适用于HTTPS URL(例如“ https://www.google.com
”)!我收到java.io.IOException: Unable to tunnel through proxy. Proxy returns "HTTP/1.0 407 Proxy Authentication Required"
的时候我尝试访问HTTPS URL。
此代码适用于HTTP和HTTPS:
URL url = new URL("https://www.google.com");
HttpURLConnection httpURLConnection = null;
InetSocketAddress proxyLocation = new InetSocketAddress(proxyHost, proxyPort);
Proxy proxy = new Proxy(Proxy.Type.HTTP, proxyLocation);
httpURLConnection = (HttpURLConnection) url.openConnection(proxy);
// Works for HTTP and HTTPS, but sets a global default!
Authenticator.setDefault(new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(proxyUserName, proxyPassword.toCharArray());
}
});
InputStream is = httpURLConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int data = isr.read();
while(data != -1){
char c = (char) data;
data = isr.read();
System.out.print(c);
}
isr.close();
第二个代码的问题在于它设置了一个新的默认值,Authenticator
而我不想这样做,因为此代理仅由应用程序的一部分使用,而应用程序的不同部分可能正在使用其他代理。我不想为整个应用程序设置全局默认值。有没有一种方法可以让第一个代码与HTTPS一起使用,或者有一种方法可以在Authenticator
不将其设置为默认值的情况下使用它?
我必须使用java.net.HttpURLConnection
,因为我要重写必须返回an的类的方法HttpURLConnection
,所以我不能使用Apache
HttpClient。
您可以自己扩展ProxiedHttpsConnection
和处理所有与底层相关的内容。
需要执行以下步骤以通过HTTP代理与https网站建立连接:
注意:与代理服务器和http服务器的通信应使用ASCII7。
CONNECT stackoverflow.com:443 HTTP/1.0\r\n
给代理Proxy-Authorization: Basic c2F5WW91SGF2ZVNlZW5UaGlzSW5UaGVDb21tZW50cw==\r\n
。\r\n
HTTP/1.0 200
。GET /questions/3304006/persistent-httpurlconnection-in-java HTTP/1.0\r\n
Host: stackoverflow.com\r\n
\r\n
\r\n
并将第一行解析为状态消息当我们想要实现HttpUrlConnection类时,我们还需要考虑以下几点:
OutputStream
意味着数据传输已经完成,而不是意味着连接必须完成迅速地说,有很多陷阱
在我设计的类中,它使用布尔标志来记住connect
方法和afterPostClosure
方法是否被调用,并且还具有getInputStream()
在OutputStream
关闭之前调用if的支持。
此类还对套接字返回的流使用了尽可能少的包装,以防止过于复杂。
public class ProxiedHttpsConnection extends HttpURLConnection {
private final String proxyHost;
private final int proxyPort;
private static final byte[] NEWLINE = "\r\n".getBytes();//should be "ASCII7"
private Socket socket;
private final Map<String, List<String>> headers = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
private final Map<String, List<String>> sendheaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
private final Map<String, List<String>> proxyheaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
private final Map<String, List<String>> proxyreturnheaders = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
private int statusCode;
private String statusLine;
private boolean isDoneWriting;
public ProxiedHttpsConnection(URL url,
String proxyHost, int proxyPort, String username, String password)
throws IOException {
super(url);
socket = new Socket();
this.proxyHost = proxyHost;
this.proxyPort = proxyPort;
String encoded = Base64.encode((username + ":" + password).getBytes())
.replace("\r\n", "");
proxyheaders.put("Proxy-Authorization", new ArrayList<>(Arrays.asList("Basic " + encoded)));
}
@Override
public OutputStream getOutputStream() throws IOException {
connect();
afterWrite();
return new FilterOutputStream(socket.getOutputStream()) {
@Override
public void write(byte[] b, int off, int len) throws IOException {
out.write(String.valueOf(len).getBytes());
out.write(NEWLINE);
out.write(b, off, len);
out.write(NEWLINE);
}
@Override
public void write(byte[] b) throws IOException {
out.write(String.valueOf(b.length).getBytes());
out.write(NEWLINE);
out.write(b);
out.write(NEWLINE);
}
@Override
public void write(int b) throws IOException {
out.write(String.valueOf(1).getBytes());
out.write(NEWLINE);
out.write(b);
out.write(NEWLINE);
}
@Override
public void close() throws IOException {
afterWrite();
}
};
}
private boolean afterwritten = false;
@Override
public InputStream getInputStream() throws IOException {
connect();
return socket.getInputStream();
}
@Override
public void setRequestMethod(String method) throws ProtocolException {
this.method = method;
}
@Override
public void setRequestProperty(String key, String value) {
sendheaders.put(key, new ArrayList<>(Arrays.asList(value)));
}
@Override
public void addRequestProperty(String key, String value) {
sendheaders.computeIfAbsent(key, l -> new ArrayList<>()).add(value);
}
@Override
public Map<String, List<String>> getHeaderFields() {
return headers;
}
@Override
public void connect() throws IOException {
if (connected) {
return;
}
connected = true;
socket.setSoTimeout(getReadTimeout());
socket.connect(new InetSocketAddress(proxyHost, proxyPort), getConnectTimeout());
StringBuilder msg = new StringBuilder();
msg.append("CONNECT ");
msg.append(url.getHost());
msg.append(':');
msg.append(url.getPort() == -1 ? 443 : url.getPort());
msg.append(" HTTP/1.0\r\n");
for (Map.Entry<String, List<String>> header : proxyheaders.entrySet()) {
for (String l : header.getValue()) {
msg.append(header.getKey()).append(": ").append(l);
msg.append("\r\n");
}
}
msg.append("Connection: close\r\n");
msg.append("\r\n");
byte[] bytes;
try {
bytes = msg.toString().getBytes("ASCII7");
} catch (UnsupportedEncodingException ignored) {
bytes = msg.toString().getBytes();
}
socket.getOutputStream().write(bytes);
socket.getOutputStream().flush();
byte reply[] = new byte[200];
byte header[] = new byte[200];
int replyLen = 0;
int headerLen = 0;
int newlinesSeen = 0;
boolean headerDone = false;
/* Done on first newline */
InputStream in = socket.getInputStream();
while (newlinesSeen < 2) {
int i = in.read();
if (i < 0) {
throw new IOException("Unexpected EOF from remote server");
}
if (i == '\n') {
if (newlinesSeen != 0) {
String h = new String(header, 0, headerLen);
String[] split = h.split(": ");
if (split.length != 1) {
proxyreturnheaders.computeIfAbsent(split[0], l -> new ArrayList<>()).add(split[1]);
}
}
headerDone = true;
++newlinesSeen;
headerLen = 0;
} else if (i != '\r') {
newlinesSeen = 0;
if (!headerDone && replyLen < reply.length) {
reply[replyLen++] = (byte) i;
} else if (headerLen < reply.length) {
header[headerLen++] = (byte) i;
}
}
}
String replyStr;
try {
replyStr = new String(reply, 0, replyLen, "ASCII7");
} catch (UnsupportedEncodingException ignored) {
replyStr = new String(reply, 0, replyLen);
}
// Some proxies return http/1.1, some http/1.0 even we asked for 1.0
if (!replyStr.startsWith("HTTP/1.0 200") && !replyStr.startsWith("HTTP/1.1 200")) {
throw new IOException("Unable to tunnel. Proxy returns \"" + replyStr + "\"");
}
SSLSocket s = (SSLSocket) ((SSLSocketFactory) SSLSocketFactory.getDefault())
.createSocket(socket, url.getHost(), url.getPort(), true);
s.startHandshake();
socket = s;
msg.setLength(0);
msg.append(method);
msg.append(" ");
msg.append(url.toExternalForm().split(String.valueOf(url.getPort()), -2)[1]);
msg.append(" HTTP/1.0\r\n");
for (Map.Entry<String, List<String>> h : sendheaders.entrySet()) {
for (String l : h.getValue()) {
msg.append(h.getKey()).append(": ").append(l);
msg.append("\r\n");
}
}
if (method.equals("POST") || method.equals("PUT")) {
msg.append("Transfer-Encoding: Chunked\r\n");
}
msg.append("Host: ").append(url.getHost()).append("\r\n");
msg.append("Connection: close\r\n");
msg.append("\r\n");
try {
bytes = msg.toString().getBytes("ASCII7");
} catch (UnsupportedEncodingException ignored) {
bytes = msg.toString().getBytes();
}
socket.getOutputStream().write(bytes);
socket.getOutputStream().flush();
}
private void afterWrite() throws IOException {
if (afterwritten) {
return;
}
afterwritten = true;
socket.getOutputStream().write(String.valueOf(0).getBytes());
socket.getOutputStream().write(NEWLINE);
socket.getOutputStream().write(NEWLINE);
byte reply[] = new byte[200];
byte header[] = new byte[200];
int replyLen = 0;
int headerLen = 0;
int newlinesSeen = 0;
boolean headerDone = false;
/* Done on first newline */
InputStream in = socket.getInputStream();
while (newlinesSeen < 2) {
int i = in.read();
if (i < 0) {
throw new IOException("Unexpected EOF from remote server");
}
if (i == '\n') {
if (headerDone) {
String h = new String(header, 0, headerLen);
String[] split = h.split(": ");
if (split.length != 1) {
headers.computeIfAbsent(split[0], l -> new ArrayList<>()).add(split[1]);
}
}
headerDone = true;
++newlinesSeen;
headerLen = 0;
} else if (i != '\r') {
newlinesSeen = 0;
if (!headerDone && replyLen < reply.length) {
reply[replyLen++] = (byte) i;
} else if (headerLen < header.length) {
header[headerLen++] = (byte) i;
}
}
}
String replyStr;
try {
replyStr = new String(reply, 0, replyLen, "ASCII7");
} catch (UnsupportedEncodingException ignored) {
replyStr = new String(reply, 0, replyLen);
}
/* We asked for HTTP/1.0, so we should get that back */
if ((!replyStr.startsWith("HTTP/1.0 200")) && !replyStr.startsWith("HTTP/1.1 200")) {
throw new IOException("Server returns \"" + replyStr + "\"");
}
}
@Override
public void disconnect() {
try {
socket.close();
} catch (IOException ex) {
Logger.getLogger(ProxiedHttpsConnection.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Override
public boolean usingProxy() {
return true;
}
}
上面代码的当前错误:
上面的代码可以像这样使用:
ProxiedHttpsConnection n = new ProxiedHttpsConnection(
new URL("https://stackoverflow.com:443/questions/3304006/persistent-httpurlconnection-in-java"),
"proxy.example.com", 8080, "root", "flg83yvem#");
n.setRequestMethod("GET");
n.addRequestProperty("User-Agent", "Java test https://stackoverflow.com/users/1542723/ferrybig");
//try (OutputStream out = n.getOutputStream()) {
// out.write("Hello?".getBytes());
//}
try (InputStream in = n.getInputStream()) {
byte[] buff = new byte[1024];
int length;
while ((length = in.read(buff)) >= 0) {
System.out.write(buff, 0, length);
}
}
如果要将它与一种代理选择器一起使用,则应检查url的协议,以查看其http还是https,如果它的http,则不要使用此类,而是手动附加标头,例如:
httpURLConnection.setRequestProperty("Proxy-Authorization", "Basic " + encoded);
为什么不使用httpsUrlConnection.setSSLSocketFactory
虽然Java有此方法,但尝试使用它会向您展示为什么它不起作用,但Java只会createSocket(Socket s, String host, int port, boolean autoClose)
通过已打开的连接不断调用,从而无法手动进行代理操作。
问题内容: 我需要使用PostForm方法将代理与auth一起使用。如果我使用类似(简体)的内容: 我可以轻松做到,并且效果很好。但是现在,我正在编辑第三方程序包,并尝试将代理添加到现有代码中: 在我看来,它是行不通的,而且失败了。在此示例中,没有身份验证的代理可以正常工作。有人知道吗,在这种情况下我可以在auth中使用代理吗? 问题答案: 您正在尝试向响应中添加标头,这不是您发送到服务器的内容,
我尝试了angular.js,并从一个restful api的web-ui开始(使用超文本传输协议基本授权)。这真的很好,除了授权工作。 到目前为止,我使用的是设置密码,但大多数情况下浏览器会打开http basic auth的默认登录表单。另一个奇怪的行为是angular请求不包含授权头(选项和GET请求都不包含)。我还尝试使用header配置在每个请求上设置此header,但这也不起作用。 有
问题内容: 我想为在Ubuntu服务器12.04.1上运行的Apache的反向代理站点添加基本身份验证。 该Web应用程序是在Java EE容器上运行的Jenkins。 我在 httpd.conf中 添加了以下配置, 当我使用错误的密码或不存在的用户名进行身份验证时,我可以在apache的 error.log 中找到以下消息, [2012年10月27日星期六17:51:59] [错误] [客户端2
问题内容: 问题: 如何向OkHTTP添加授权代理。 我知道OkHTTP的生成器确实支持代理,尽管我很难设置一个代理。 我有IP /端口/用户名/密码。 尽管我不知道如何将其转换为client.SetProxy()中可以使用的那些。 这似乎过于复杂,我似乎无法弄清楚。任何帮助,将不胜感激。 问题答案: 试试这个:
问题内容: 我一直在尝试使用Apaches HttpComponent的httpclient时从配置的属性中配置用于代理身份验证的用户和密码,但是没有成功。我发现的所有示例都引用了不再可用的方法和类,例如和。 因此,谁能给我一个有关如何配置代理凭据的示例? 问题答案: 对于Basic-Auth,它看起来像这样: 开箱即用不支持AFAIK NTLM。但是您也许可以使用过载来管理它。
问题内容: 我想写书,所使用的一个一个的NodeJS REST的API服务器Joyent的,并且一切正常,除了我无法验证普通用户的身份验证。如果我跳到终端并执行,则无法在NodeJS http服务器上获取值username:password。如果我的NodeJS http服务器类似于 ,是否应该在来自回调的 req 对象中某处获取值username:password ?如何获得这些值而不必使用Co