我遇到了一个非常奇怪的问题。编写一个应用程序从 Internet 下载一些数据并支持代理服务器 我决定使用 Apache 的 HttpClient 库。 jar 二进制文件已成功添加到 NetBeans 项目,并且在一个简单的应用程序中执行了以下代码片段(也成功执行):
DefaultHttpClient httpclient = new DefaultHttpClient();
String proxyHost = "192.168.4.10";
Integer proxyPort = 8080;
HttpHost targetHost = new HttpHost("noaasis.noaa.gov", 80, "http");
HttpGet httpget = new HttpGet("/ptbus/ptbus167");
try {
HttpHost proxy = new HttpHost(proxyHost, proxyPort);
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
System.out.println("executing request: " + httpget.getRequestLine());
System.out.println("via proxy: " + proxy);
System.out.println("to target: " + targetHost);
HttpResponse response = httpclient.execute(targetHost, httpget);
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
Header[] headers = response.getAllHeaders();
for (int i = 0; i<headers.length; i++) {
System.out.println(headers[i]);
}
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
}
catch (IOException ex) {
}
finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
但是当我尝试在 Swing 应用程序中做同样的事情时,它不起作用。例如,重写默认的 Netbeans 桌面应用程序的“关于” Action 监听器如下
@Action
public void showAboutBox() {
new Thread(new Runnable() {
public void run() {
DefaultHttpClient httpclient = new DefaultHttpClient();
......
......
......
finally {
// When HttpClient instance is no longer needed,
// shut down the connection manager to ensure
// immediate deallocation of all system resources
httpclient.getConnectionManager().shutdown();
}
}
}).start();
}
导致应用程序的执行停止在某处
HttpResponse response = httpclient.execute(targetHost, httpget);
至少,它永远不会返回...
有趣的是,如果我在创建任何 Swing 实例之前也将此代码片段放入应用程序的主要方法中,则会传递上述行并接收 HTTP 响应。然后调用 showAboutBox() 不再导致问题 - 我也收到 HTTP 响应。
伙计们,我做错了什么?有什么窍门?我可以在我的 Swing 应用程序中使用 Apache 的库吗?我无法理解发生了什么,也没有在网上找到与此类似的花费时间。
谢谢关注。希望得到任何帮助!
最佳答案
您正在阻止 event dispatch thread (美东时间)。使用 SwingWorker
,如图here .
关于java - Apache 的 HttpClient 在 Swing 应用程序中睡着了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6473024/