0

我希望通过 Apache HttpClient 4.1.2 在雅虎汇率服务上执行 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 作为输入,以及为什么。

4

1 回答 1

0

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

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

于 2012-05-04T06:08:22.180 回答