【问题标题】:Proxy Username/Password in Apache HttpClientApache HttpClient 中的代理用户名/密码
【发布时间】:2012-05-04 05:59:30
【问题描述】:

我希望通过 Apache HttpClient 4.1.2 对 yahoo 汇率服务执行 GET,但是当我通过公司防火墙访问时,我收到了 UknownHostException。不过,当我在家中尝试时,代码运行良好(当然,没有任何代理配置)。

此外,该 URL 会在我的浏览器中打开,但无法从命令提示符 ping。

示例 URL 为 http://quote.yahoo.com/d/quotes.csv?f=l1&s=USDINR=X

编辑 2:这是我用来连接到雅虎金融服务的完整代码:

GetRate.java

public class GetRate {
    public static void main(String[] args) {
       final String FROM = "USD";
       final String TO = "INR";

       ArrayList<String> paramsList = new ArrayList<String>();
            paramsList.add(FROM + TO);
            System.out.println("Tracking "+ TO + " vs. " + FROM + " Exchange Rate...");

       try {
                double _new = new Double(RestClient.doGet(paramsList));
           double _old = _new;

           while(true) {
               _new = new Double(RestClient.doGet(paramsList));
                    if(_old != _new)
                        _old = _new;
               Thread.sleep(1000);
            }
         } catch (HttpException e) {
                  e.printStackTrace();
         } catch (IOException e) {
        e.printStackTrace();
         } catch (URISyntaxException e) {
        e.printStackTrace();
         } catch (InterruptedException e) {
        e.printStackTrace();
         }
        }
}

RestClient.java

public class RestClient {
public static final int HTTP_OK = 200;
public static final String SERVER_URL = "http://quote.yahoo.com/d/quotes.csv";
public static final String DEFAULT_ENCODING = "UTF-8";

public static String doGet(final ArrayList<String> params) throws HttpException,
        IOException, URISyntaxException {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpConnectionParams
            .setConnectionTimeout(httpClient.getParams(), 10000);

    httpClient = proxyConfig(httpClient);

    HttpHost targetHost = new HttpHost(SERVER_URL);
    String urlParams = "?f=l1";
    if(!params.isEmpty()) {
        for(String param : params) {
            String paramString = "s=" + URLEncoder.encode(param, DEFAULT_ENCODING) + "=X";
            urlParams += (urlParams.length() > 1) ? ("&" + paramString) : paramString;
        }
    }
    HttpGet httpget = new HttpGet(urlParams);

    System.out.println("Final URL: " + httpget.getURI().toString());

    HttpResponse response = httpClient.execute(targetHost, httpget);
    HttpEntity entity = response.getEntity();
    InputStream instream = entity.getContent();
    return read(instream);
}

private static String read(InputStream in) throws IOException {
    StringBuilder sb = new StringBuilder();
    BufferedReader r = new BufferedReader(new InputStreamReader(in), 1000);
    for (String line = r.readLine(); line != null; line = r.readLine()) {
        sb.append(line + ",");
    }
    in.close();
    return sb.toString().substring(0, sb.length() - 1);
}

     /** Proxy config Approach 1 */
private static DefaultHttpClient proxyConfig(DefaultHttpClient httpClient) {    
    AuthScope auth = new AuthScope("proxy.tcs.com", 8080);
    Credentials creds = new UsernamePasswordCredentials("USER_NAME", "PASSWORD");
    httpClient.getCredentialsProvider().setCredentials(auth, creds);

    return httpClient;
}
}        for(String param : params) {
             String paramString = "s=" + URLEncoder.encode(param, DEFAULT_ENCODING) + "=X";
             urlParams += (urlParams.length() > 1) ? ("&" + paramString) : paramString;
     }
 }

 HttpGet httpget = new HttpGet(urlParams);
 HttpResponse response = httpClient.execute(targetHost, httpget);
 HttpEntity entity = response.getEntity();
 InputStream instream = entity.getContent();

方法 2:我也尝试了以下代理配置,但找不到如何添加用户名/密码。

/** Proxy config Approach 2 */
HttpHost proxy = new HttpHost("PROXY_HOST", PROXY_PORT);
httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);

谢谢,
去博吉特

编辑 1:
方法 1 的堆栈跟踪:

java.net.UnknownHostException: http://quote.yahoo.com/d/quotes.csv
at java.net.Inet6AddressImpl.lookupAllHostAddr(Native Method)
at java.net.InetAddress$1.lookupAllHostAddr(Unknown Source)
at java.net.InetAddress.getAddressFromNameService(Unknown Source)
at java.net.InetAddress.getAllByName0(Unknown Source)
at java.net.InetAddress.getAllByName(Unknown Source)
at java.net.InetAddress.getAllByName(Unknown Source)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.resolveHostname(DefaultClientConnectionOperator.java:242)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:130)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:149)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:121)
at org.apache.http.impl.client.DefaultRequestDirector.tryConnect(DefaultRequestDirector.java:573)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:425)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:820)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:776)
at ws.client.RestClient.doGet(RestClient.java:48)
at ws.client.GetRate.main(GetRate.java:22)

方法 2 的堆栈跟踪:

Exception in thread "main" java.lang.NumberFormatException: For input string: "<HEAD><TITLE>Proxy Authorization Required</TITLE></HEAD>,<BODY BGCOLOR="white" FGCOLOR="black"><H1>Proxy Authorization Required</H1><HR>,<FONT FACE="Helvetica,Arial"><B>,Description: Authorization is required for access to this proxy</B></FONT>,<HR>,<!-- default "Proxy Authorization Required" response (407) -->,</BODY>,"
at sun.misc.FloatingDecimal.readJavaFormatString(Unknown Source)
at java.lang.Double.valueOf(Unknown Source)
at java.lang.Double.<init>(Unknown Source)
at ws.client.GetRate.main(GetRate.java:22)

问题是,我不确定代码在哪里获取 HTML 作为输入,以及为什么。

【问题讨论】:

    标签: proxy httpclient apache-httpcomponents


    【解决方案1】:

    您是否在字面上使用“PROXY_HOST”作为代理构造函数?如果是这样,您必须在浏览器配置中使用代理主机。 PROXY_PORT 也一样。

    由于防火墙,您将无法从贵公司 ping Yahoo,但您可以通过浏览器访问,因为它被配置为使用代理服务器。

    【讨论】:

    • 我正在使用浏览器中的代理信息。 PROXY_HOST 只是一个占位符(一种)。
    • 好的,那么对不起我的问题;)。我没有看到您在执行呼叫之前设置代理配置。在此处查看有关如何执行此操作的示例:hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/…
    • 我已经这样做了。我的实现是基于那里的信息。但是我无法在那里查找某些方法,例如client.getState()。我假设client 指的是HttpClientDefaultHttpClient,但是这两个类中都没有这样的方法。
    • 您收到第一个错误是因为您没有正确设置 HttpHost。示例中的设置方式是HttpHost targetHost = new HttpHost("www.verisign.com", 443, "https");。您应该输入如下内容:HttpHost targetHost = new HttpHost("quote.yahoo.com",80,"http");
    • 按照指示更改HttpHost,但错误保持不变。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-25
    • 2012-10-31
    • 1970-01-01
    • 1970-01-01
    • 2017-01-20
    相关资源
    最近更新 更多