Apache HttpClient 4.1.2를 통해 yahoo 통화 요금제 서비스를 수행하려하지만 회사 방화벽을 통해 액세스 할 때 UknownHostException이 발생합니다. 비록 가정에서 (물론 프록시 설정없이) 코드를 사용해도 괜찮습니다.Apache HttpClient의 프록시 사용자 이름/암호
또한 브라우저에서 URL이 열리지 만 명령 프롬프트에서 핑 (ping) 할 수 없습니다.
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();
}
}
}
: 여기가 야후 금융 서비스에 연결하는 데 사용되는 완전한 코드의 :
샘플 URL은 http://quote.yahoo.com/d/quotes.csv?f=l1&s=USDINR=X
EDIT 2 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);
감사합니다,
Debojit
편집 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_HOST는 단지 자리 표시 자 (일종의)입니다. – Debojit
그래, 내 질문에 대해 죄송합니다;). 전화를 걸기 전에 프록시 구성을 설정하는 것을 보지 못합니다. 수행 방법에 대한 예제를 다음에서 확인하십시오. http://hc.apache.org/httpcomponents-client-ga/httpclient/examples/org/apache/http/examples/client/ClientProxyAuthentication.java – Sircom
이미 해 보았습니다. .. 내 구현은 거기에있는 정보를 기반으로합니다. 그러나 나는'client.getState()'와 같은 메소드를 찾을 수 없다. 나는'클라이언트'가'HttpClient' 또는'DefaultHttpClient'를 참조한다고 가정하고 있지만, 어느 쪽의 클래스에도 그러한 메소드가 존재하지 않습니다. – Debojit