gpt4 book ai didi

java - 使用 java 中的代理代码连接到站点

转载 作者:搜寻专家 更新时间:2023-11-01 01:05:42 29 4
gpt4 key购买 nike

我想在 java 中通过代理连接到 as 站点。这是我写的代码:

public class ConnectThroughProxy 
{
Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("proxy ip", 8080));
public static void main(String[] args)
{
try
{
URL url = new URL("http://www.rgagnon.com/javadetails/java-0085.html");
URLConnection connection=url.openConnection();
String encoded = new String(Base64.encode(new String("user_name:pass_word").getBytes()));
connection.setDoOutput(true);
connection.setRequestProperty("Proxy-Authorization","Basic "+encoded);
String page="";
String line;
StringBuffer tmp = new StringBuffer();
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
while ((line=in.readLine()) != null)
{
page.concat(line + "\n");
}
System.out.println(page);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}

在尝试运行此代码时,它会抛出以下错误:

java.lang.IllegalArgumentException: Illegal character(s) in message header value: Basic dXNlcl9uYW1lOnBhc3Nfd29yZA==
at sun.net.www.protocol.http.HttpURLConnection.checkMessageHeader(HttpURLConnection.java:323)
at sun.net.www.protocol.http.HttpURLConnection.setRequestProperty(HttpURLConnection.java:2054)
at test.ConnectThroughProxy.main(ConnectThroughProxy.java:30)

知道怎么做吗?

最佳答案

如果您只是想通过 HTTP 代理服务器发出 HTTP 请求,则无需付出如此大的努力。这里有一篇文章:http://java.sun.com/javase/6/docs/technotes/guides/net/proxies.html

但它基本上归结为仅在命令行或代码中设置 http.proxyHost 和 http.proxyPort 环境属性:

// Set the http proxy to webcache.mydomain.com:8080System.setProperty("http.proxyHost", "webcache.mydomain.com");System.setProperty("http.proxyPort", "8080");// Next connection will be through proxy.URL url = new URL("http://java.sun.com/");InputStream in = url.openStream();// Now, let's 'unset' the proxy.System.clearProperty("http.proxyHost");// From now on HTTP connections will be done directly.

关于java - 使用 java 中的代理代码连接到站点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3035973/

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