【发布时间】:2011-04-06 20:30:48
【问题描述】:
我想设置一个 http 连接来发送请求并在一个独立的 java 应用程序中获取响应,谁能帮我解决这个问题????
【问题讨论】:
-
顺便说一句,如果它对您最有帮助,请随时“接受”一个答案。 (尽管您可能是未注册用户,我不确定这是否可能?)
我想设置一个 http 连接来发送请求并在一个独立的 java 应用程序中获取响应,谁能帮我解决这个问题????
【问题讨论】:
您可以使用与标准 Java 捆绑在一起的 URLConnection 类(自 JDK 1.0 起!),或更高级别的 HTTP 客户端,例如 Apache's HTTPCLIENT,除了普通 HTTP 之外,它还提供更高级别的组件,如 cookie、标准标头等等。
【讨论】:
HttpURLConnection connection = null;
try {
URL url = new URL("www.google.com");
connection = (HttpURLConnection) url.openConnection();
connection.connect();
connection.getInputStream();
// do something with the input stream here
} catch (MalformedURLException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
} finally {
if(null != connection) { connection.disconnect(); }
}
【讨论】:
一些答案已经指出了 Apache HTTP 客户端,但它们链接到不再维护的 3.x 版本。如果你想使用这个库,你应该使用版本 4,它的 API 略有不同:http://hc.apache.org/httpcomponents-client-4.0.1/index.html
【讨论】: