Answers:
imho:Apache HTTP客户端
用法示例:
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();
}
}
}
一些重要功能:
我建议使用Apache HttpComponents HttpClient,它是Commons HttpClient的后继者
我也建议您看一下HtmlUnit。HtmlUnit是“用于Java程序的GUI更少的浏览器”。 http://htmlunit.sourceforge.net/
我偏爱泽西岛。我们在所有项目中都使用1.10,并且没有遇到无法解决的问题。
我喜欢它的一些原因:
实际上,HTTPClient和Jersey在实现和API方面非常相似。Jersey的扩展也允许它支持HTTPClient。
Jersey 1.x的一些代码示例: https //blogs.oracle.com/enterprisetechtips/entry/using_restful_web_services_with
http://www.mkyong.com/webservices/jax-rs/restful-java-client-with-jersey-client/
带有Jersey客户端的HTTPClient:https ://blogs.oracle.com/PavelBucek/entry/jersey_client_apache_http_client
我同意httpclient是一个标准的东西-但我想您正在寻找选项,因此...
Restlet提供了一个专门用于与Restful Web服务进行交互的http客户端。
示例代码:
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);
有关更多详细信息,请参见http://www.restlet.org/
我可以推荐您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>
<groupId>net.sf.corn</groupId>
<artifactId>corn-httpclient</artifactId>
<version>1.0.0</version>
</dependency>
Google HTTP Java Client对我来说不错,因为它也可以在Android和App Engine上运行。
我想提到Ning Async Http客户端库。我从未使用过它,但是与过去我一直使用的Apache Http Client相比,我的同事对此赞不绝口。我特别感兴趣的是,它基于高性能异步I / O框架Netty,对此我更加熟悉并深信。