用于 HTTP POST、GET 等的最佳 Java 库是什么?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1322335/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is the best Java library to use for HTTP POST, GET etc.?
提问by rmcc
What is the best Java library to use for HTTP POST, GET etc. in terms of performance, stability, maturity etc.? Is there one particular library that is used more than others?
在性能、稳定性、成熟度等方面,用于 HTTP POST、GET 等的最佳 Java 库是什么?是否有一个特定的库比其他库使用得更多?
My requirements are submitting HTTPS POST requests to a remote server. I have used the java.net.* package in the past as well as org.apache.commons.httpclient.* package. Both have got the job done, but I would like some of your opinions/recommendations.
我的要求是向远程服务器提交 HTTPS POST 请求。我过去使用过 java.net.* 包以及 org.apache.commons.httpclient.* 包。两者都完成了工作,但我希望得到您的一些意见/建议。
采纳答案by Chris
imho: Apache HTTP Client
恕我直言:Apache HTTP 客户端
usage example:
用法示例:
import org.apache.commons.httpclient.*;
import org.apache.commons.httpclient.methods.*;
import org.apache.commons.httpclient.params.HttpMethodParams;
import java.io.*;
public class HttpClientTutorial {
private static String url = "http://www.apache.org/";
public static void main(String[] args) {
// Create an instance of HttpClient.
HttpClient client = new HttpClient();
// Create a method instance.
GetMethod method = new GetMethod(url);
// Provide custom retry handler is necessary
method.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
new DefaultHttpMethodRetryHandler(3, false));
try {
// Execute the method.
int statusCode = client.executeMethod(method);
if (statusCode != HttpStatus.SC_OK) {
System.err.println("Method failed: " + method.getStatusLine());
}
// Read the response body.
byte[] responseBody = method.getResponseBody();
// Deal with the response.
// Use caution: ensure correct character encoding and is not binary data
System.out.println(new String(responseBody));
} catch (HttpException e) {
System.err.println("Fatal protocol violation: " + e.getMessage());
e.printStackTrace();
} catch (IOException e) {
System.err.println("Fatal transport error: " + e.getMessage());
e.printStackTrace();
} finally {
// Release the connection.
method.releaseConnection();
}
}
}
some highlight features:
一些突出特点:
- Standards based, pure Java, implementation of HTTP versions 1.0
and 1.1
- Full implementation of all HTTP methods (GET, POST, PUT, DELETE, HEAD, OPTIONS, and TRACE) in an extensible OO framework.
- Supports encryption with HTTPS (HTTP over SSL) protocol.
- Granular non-standards configuration and tracking.
- Transparent connections through HTTP proxies.
- Tunneled HTTPS connections through HTTP proxies, via the CONNECT method.
- Transparent connections through SOCKS proxies (version 4 & 5) using native Java socket support.
- Authentication using Basic, Digest and the encrypting NTLM (NT Lan Manager) methods.
- Plug-in mechanism for custom authentication methods.
- Multi-Part form POST for uploading large files.
- Pluggable secure sockets implementations, making it easier to use third party solutions
- Connection management support for use in multi-threaded applications. Supports setting the maximum total connections as well as the maximum connections per host. Detects and closes stale connections.
- Automatic Cookie handling for reading Set-Cookie: headers from the server and sending them back out in a Cookie: header when appropriate.
- Plug-in mechanism for custom cookie policies.
- Request output streams to avoid buffering any content body by streaming directly to the socket to the server.
- Response input streams to efficiently read the response body by streaming directly from the socket to the server.
- Persistent connections using KeepAlive in HTTP/1.0 and persistance in HTTP/1.1
- Direct access to the response code and headers sent by the server.
- The ability to set connection timeouts.
- HttpMethods implement the Command Pattern to allow for parallel requests and efficient re-use of connections.
- Source code is freely available under the Apache Software License.
- 基于标准,纯 Java,HTTP 版本 1.0 和 1.1 的实现
- 在可扩展的 OO 框架中完全实现所有 HTTP 方法(GET、POST、PUT、DELETE、HEAD、OPTIONS 和 TRACE)。
- 支持使用 HTTPS(HTTP over SSL)协议进行加密。
- 细粒度的非标准配置和跟踪。
- 通过 HTTP 代理的透明连接。
- 使用 CONNECT 方法通过 HTTP 代理建立隧道 HTTPS 连接。
- 使用原生 Java 套接字支持通过 SOCKS 代理(版本 4 和 5)的透明连接。
- 使用基本、摘要和加密 NTLM (NT Lan Manager) 方法进行身份验证。
- 自定义身份验证方法的插件机制。
- 用于上传大文件的多部分表单 POST。
- 可插拔的安全套接字实现,更容易使用第三方解决方案
- 用于多线程应用程序的连接管理支持。支持设置最大总连接数以及每台主机的最大连接数。检测并关闭陈旧的连接。
- 自动 Cookie 处理,用于从服务器读取 Set-Cookie: 标头并在适当时将它们在 Cookie: 标头中发送回。
- 自定义 cookie 策略的插件机制。
- 请求输出流以避免通过直接流到服务器的套接字来缓冲任何内容主体。
- 响应输入流通过直接从套接字流到服务器来有效地读取响应正文。
- 在 HTTP/1.0 中使用 KeepAlive 的持久连接和在 HTTP/1.1 中的持久性
- 直接访问服务器发送的响应代码和标头。
- 设置连接超时的能力。
- HttpMethods 实现命令模式以允许并行请求和有效的连接重用。
- 源代码可在 Apache 软件许可下免费获得。
回答by Pablojim
I agree httpclient is something of a standard - but I guess you are looking for options so...
我同意 httpclient 是一种标准 - 但我猜你正在寻找选项所以......
Restlet provides a http client specially designed for interactong with Restful web services.
Restlet 提供了一个专门为与 Restful web 服务交互而设计的 http 客户端。
Example code:
示例代码:
Client client = new Client(Protocol.HTTP);
Request r = new Request();
r.setResourceRef("http://127.0.0.1:8182/sample");
r.setMethod(Method.GET);
r.getClientInfo().getAcceptedMediaTypes().add(new Preference<MediaType>(MediaType.TEXT_XML));
client.handle(r).getEntity().write(System.out);
See http://www.restlet.org/for more details
有关更多详细信息,请参阅http://www.restlet.org/
回答by Adil
I would recommend Apache HttpComponents HttpClient, a successor of Commons HttpClient
我会推荐Apache HttpComponents HttpClient,它是Commons HttpClient的继承者
I would also recommend to take a look at HtmlUnit. HtmlUnit is a "GUI-Less browser for Java programs". http://htmlunit.sourceforge.net/
我还建议看看 HtmlUnit。HtmlUnit 是一个“用于 Java 程序的无 GUI 浏览器”。 http://htmlunit.sourceforge.net/
回答by ElMattIO
I'm somewhat partial to Jersey. We use 1.10 in all our projects and haven't run into an issue we couldn't solve with it.
我有点偏爱Jersey。我们在所有项目中都使用 1.10,并且没有遇到我们无法解决的问题。
Some reasons why I like it:
我喜欢它的一些原因:
- Providers - created soap 1.1/1.2 providers in Jersey and have eliminated the need to use the bulky AXIS for our JAX-WS calls
- Filters - created database logging filters to log the entire request (including the request/response headers) while preventing logging of sensitive information.
- JAXB - supports marshaling to/from objects straight from the request/response
- API is easy to use
- Providers - 在 Jersey 中创建了 soap 1.1/1.2 提供程序,并消除了使用庞大的 AXIS 进行 JAX-WS 调用的需要
- 过滤器 - 创建数据库日志过滤器以记录整个请求(包括请求/响应标头),同时防止记录敏感信息。
- JAXB - 支持直接从请求/响应到/从对象封送
- API易于使用
In truth, HTTPClient and Jersey are very similar in implementation and API. There is also an extension for Jersey that allows it to support HTTPClient.
事实上,HTTPClient 和 Jersey 在实现和 API 上非常相似。Jersey 还有一个扩展,允许它支持 HTTPClient。
Some code samples with Jersey 1.x: https://blogs.oracle.com/enterprisetechtips/entry/consuming_restful_web_services_with
Jersey 1.x 的一些代码示例:https: //blogs.oracle.com/enterprisetechtips/entry/sumption_restful_web_services_with
http://www.mkyong.com/webservices/jax-rs/restful-java-client-with-jersey-client/
http://www.mkyong.com/webservices/jax-rs/restful-java-client-with-jersey-client/
HTTPClient with Jersey Client: https://blogs.oracle.com/PavelBucek/entry/jersey_client_apache_http_client
带有 Jersey 客户端的 HTTPClient:https://blogs.oracle.com/PavelBucek/entry/jersey_client_apache_http_client
回答by Serhat
May I recommend you corn-httpclient. It's simple,fast and enough for most cases.
我可以推荐你corn-httpclient。对于大多数情况,它简单、快速且足够。
HttpForm form = new HttpForm(new URI("http://localhost:8080/test/formtest.jsp"));
//Authentication form.setCredentials("user1", "password");
form.putFieldValue("input1", "your value");
HttpResponse response = form.doPost();
assertFalse(response.hasError());
assertNotNull(response.getData());
assertTrue(response.getData().contains("received " + val));
maven dependency
Maven 依赖
<dependency>
<groupId>net.sf.corn</groupId>
<artifactId>corn-httpclient</artifactId>
<version>1.0.0</version>
</dependency>
回答by Umair A.
Google HTTP Java Clientlooks good to me because it can run on Android and App Engine as well.
Google HTTP Java Client对我来说看起来不错,因为它也可以在 Android 和 App Engine 上运行。
回答by Josh
I want to mention the Ning Async Http Client Library. I've never used it but my colleague raves about it as compared to the Apache Http Client, which I've always used in the past. I was particularly interested to learn it is based on Netty, the high-performance asynchronous i/o framework, with which I am more familiar and hold in high esteem.
我想提一下Ning Async Http Client Library。我从未使用过它,但与我过去一直使用的 Apache Http Client 相比,我的同事对它赞不绝口。我特别感兴趣的是它是基于Netty 的,高性能异步 I/O 框架,我对它更加熟悉和推崇。