什么是用于HTTP POST、GET等的最佳Java库?

时间:2021-02-22 20:22:20

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.common .httpclient.*包。双方都完成了工作,但我想听听你的意见/建议。

7 个解决方案

#1


87  

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.
    • 在可扩展的OO框架中充分实现所有HTTP方法(GET、POST、PUT、DELETE、HEAD、OPTIONS和TRACE)。
    • Supports encryption with HTTPS (HTTP over SSL) protocol.
    • 支持使用HTTPS (HTTP / SSL)协议进行加密。
    • Granular non-standards configuration and tracking.
    • 粒状非标准配置和跟踪。
    • Transparent connections through HTTP proxies.
    • 通过HTTP代理的透明连接。
    • Tunneled HTTPS connections through HTTP proxies, via the CONNECT method.
    • 通过HTTP代理(通过CONNECT方法)实现加密的HTTPS连接。
    • Transparent connections through SOCKS proxies (version 4 & 5) using native Java socket support.
    • 使用本地Java套接字支持通过SOCKS代理(版本4和5)进行透明连接。
    • Authentication using Basic, Digest and the encrypting NTLM (NT Lan Manager) methods.
    • 使用基本、摘要和加密NTLM (NT Lan Manager)方法进行身份验证。
    • 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.
    • 用于读取Set-Cookie的自动Cookie处理:来自服务器的头文件,并在适当的时候以Cookie: header发送回来。
    • Plug-in mechanism for custom cookie policies.
    • 自定义cookie策略的插件机制。
    • 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
    • 在HTTP/1.0中使用KeepAlive的持久连接,在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.
    • HttpMethods实现了命令模式,允许并行请求和高效重用连接。
    • Source code is freely available under the Apache Software License.
    • 源代码可以在Apache软件许可证下免费获得。
  • 基于标准的纯Java, HTTP版本1.0的实现和1.1在可扩展OO框架中实现所有HTTP方法(GET、POST、PUT、DELETE、HEAD、OPTIONS和TRACE)的完整实现。支持通过HTTPS (HTTP / SSL)协议进行加密。粒度非标准配置和跟踪。通过HTTP代理的透明连接。通过HTTP代理(通过CONNECT方法)实现加密的HTTPS连接。使用本地Java套接字支持通过SOCKS代理(版本4和5)进行透明连接。使用基本、摘要和加密NTLM (NT Lan Manager)方法进行身份验证。自定义身份验证方法的插件机制。多部分形式的上传大文件。可插入的安全套接字实现,使使用第三方解决方案连接管理支持在多线程应用程序中更容易。支持设置最大总连接和每个主机的最大连接。检测并关闭陈旧的连接。用于读取Set-Cookie的自动Cookie处理:来自服务器的头文件,并在适当的时候以Cookie: header发送回来。自定义cookie策略的插件机制。请求输出流,以避免通过直接流到服务器的套接字来缓冲任何内容主体。响应输入流通过直接从套接字流到服务器来有效地读取响应体。在HTTP/1.0中使用KeepAlive的持久连接,在HTTP/1.1中使用persistance直接访问服务器发送的响应代码和报头。设置连接超时的能力。HttpMethods实现了命令模式,允许并行请求和有效重用连接。源代码可以在Apache软件许可证下免费获得。

#2


18  

I would recommend Apache HttpComponents HttpClient, a successor of Commons HttpClient

我推荐Apache httpcomponent 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/

#3


15  

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.

我有点偏爱新泽西。我们在所有的项目中都使用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
  • 提供者——在Jersey中创建了soap 1.1/1.2提供者,并且已经消除了使用大轴进行JAX-WS调用的需要
  • 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
  • JAXB -支持直接从请求/响应对对象进行封送
  • API is easy to use
  • 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/consuming_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 Client的https://blogs.oracle.com/PavelBucek/entry/jersey_client_apache_http_client

#4


9  

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服务的interactong设计的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/

#5


5  

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>

#6


2  

Google HTTP Java Client looks good to me because it can run on Android and App Engine as well.

谷歌HTTP Java客户端在我看来很不错,因为它可以在Android和App引擎上运行。

#7


1  

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异步Http客户端库。我从未使用过它,但与Apache Http客户机相比,我的同事对它赞不绝口,我过去一直使用Apache Http客户机。我特别感兴趣的是,它是基于Netty,高性能的异步I /o框架,我更熟悉并保持高度的尊重。

#1


87  

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.
    • 在可扩展的OO框架中充分实现所有HTTP方法(GET、POST、PUT、DELETE、HEAD、OPTIONS和TRACE)。
    • Supports encryption with HTTPS (HTTP over SSL) protocol.
    • 支持使用HTTPS (HTTP / SSL)协议进行加密。
    • Granular non-standards configuration and tracking.
    • 粒状非标准配置和跟踪。
    • Transparent connections through HTTP proxies.
    • 通过HTTP代理的透明连接。
    • Tunneled HTTPS connections through HTTP proxies, via the CONNECT method.
    • 通过HTTP代理(通过CONNECT方法)实现加密的HTTPS连接。
    • Transparent connections through SOCKS proxies (version 4 & 5) using native Java socket support.
    • 使用本地Java套接字支持通过SOCKS代理(版本4和5)进行透明连接。
    • Authentication using Basic, Digest and the encrypting NTLM (NT Lan Manager) methods.
    • 使用基本、摘要和加密NTLM (NT Lan Manager)方法进行身份验证。
    • 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.
    • 用于读取Set-Cookie的自动Cookie处理:来自服务器的头文件,并在适当的时候以Cookie: header发送回来。
    • Plug-in mechanism for custom cookie policies.
    • 自定义cookie策略的插件机制。
    • 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
    • 在HTTP/1.0中使用KeepAlive的持久连接,在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.
    • HttpMethods实现了命令模式,允许并行请求和高效重用连接。
    • Source code is freely available under the Apache Software License.
    • 源代码可以在Apache软件许可证下免费获得。
  • 基于标准的纯Java, HTTP版本1.0的实现和1.1在可扩展OO框架中实现所有HTTP方法(GET、POST、PUT、DELETE、HEAD、OPTIONS和TRACE)的完整实现。支持通过HTTPS (HTTP / SSL)协议进行加密。粒度非标准配置和跟踪。通过HTTP代理的透明连接。通过HTTP代理(通过CONNECT方法)实现加密的HTTPS连接。使用本地Java套接字支持通过SOCKS代理(版本4和5)进行透明连接。使用基本、摘要和加密NTLM (NT Lan Manager)方法进行身份验证。自定义身份验证方法的插件机制。多部分形式的上传大文件。可插入的安全套接字实现,使使用第三方解决方案连接管理支持在多线程应用程序中更容易。支持设置最大总连接和每个主机的最大连接。检测并关闭陈旧的连接。用于读取Set-Cookie的自动Cookie处理:来自服务器的头文件,并在适当的时候以Cookie: header发送回来。自定义cookie策略的插件机制。请求输出流,以避免通过直接流到服务器的套接字来缓冲任何内容主体。响应输入流通过直接从套接字流到服务器来有效地读取响应体。在HTTP/1.0中使用KeepAlive的持久连接,在HTTP/1.1中使用persistance直接访问服务器发送的响应代码和报头。设置连接超时的能力。HttpMethods实现了命令模式,允许并行请求和有效重用连接。源代码可以在Apache软件许可证下免费获得。

#2


18  

I would recommend Apache HttpComponents HttpClient, a successor of Commons HttpClient

我推荐Apache httpcomponent 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/

#3


15  

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.

我有点偏爱新泽西。我们在所有的项目中都使用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
  • 提供者——在Jersey中创建了soap 1.1/1.2提供者,并且已经消除了使用大轴进行JAX-WS调用的需要
  • 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
  • JAXB -支持直接从请求/响应对对象进行封送
  • API is easy to use
  • 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/consuming_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 Client的https://blogs.oracle.com/PavelBucek/entry/jersey_client_apache_http_client

#4


9  

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服务的interactong设计的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/

#5


5  

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>

#6


2  

Google HTTP Java Client looks good to me because it can run on Android and App Engine as well.

谷歌HTTP Java客户端在我看来很不错,因为它可以在Android和App引擎上运行。

#7


1  

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异步Http客户端库。我从未使用过它,但与Apache Http客户机相比,我的同事对它赞不绝口,我过去一直使用Apache Http客户机。我特别感兴趣的是,它是基于Netty,高性能的异步I /o框架,我更熟悉并保持高度的尊重。