Java 异步 HTTP 客户端 [英] Asynchronous HTTP Client for Java
问题描述
作为 Java 世界中的一个相对新手,我发现许多在许多其他框架中相对微不足道的事情令人沮丧地难以完成.一个主要示例是异步 http 请求的简单解决方案.看到一个似乎并不存在,最好的方法是什么?使用像 httpclient 这样的阻塞类型库或内置的 java http 东西创建我自己的线程,或者我应该使用较新的非阻塞 io java 东西 - 对于应该简单的东西来说似乎特别复杂.
As a relative newbie in the Java world, I am finding many things frustratingly obtuse to accomplish that are relatively trivial in many other frameworks. A primary example is a simple solution for asynchronous http requests. Seeing as one doesn't seem to already exist, what is the best approach? Creating my own threads using a blocking type lib like httpclient or the built-in java http stuff, or should I use the newer non-blocking io java stuff - it seems particularly complex for something which should be simple.
我正在寻找的是从开发人员的角度来看易于使用的东西 - 类似于 AS3 中的 URLLoader - 您只需创建一个 URLRequest - 附加一堆事件处理程序来处理完成、错误、进度等, 并调用一个方法将其关闭.
What I am looking for is something easy to use from a developer point of view - something similar to URLLoader in AS3 - where you simply create a URLRequest - attach a bunch of event handlers to handle the completion, errors, progress, etc, and call a method to fire it off.
如果你不熟悉 AS3 中的 URLLoader,它非常简单,看起来像这样:
If you are not familiar with URLLoader in AS3, its so super easy and looks something like this:
private void getURL(String url)
{
URLLoader loader = new URLLoader();
loader.addEventListener(Event.Complete, completeHandler);
loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler);
loader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
URLRequest request = new URLRequest(url);
// fire it off - this is asynchronous so we handle
// completion with event handlers
loader.load(request);
}
private void completeHandler(Event event)
{
URLLoader loader = (URLLoader)event.target;
Object results = loader.data;
// process results
}
private void httpStatusHandler(Event event)
{
// check status code
}
private void ioErrorHandler(Event event)
{
// handle errors
}
推荐答案
使用以前称为 ning http 客户端库的Async Http Client".看http://code.ning.com/2010/03/introducing-nings-asynchronous-http-client-library/
Use the "Async Http Client" formerly called ning http client library. See http://code.ning.com/2010/03/introducing-nings-asynchronous-http-client-library/
现已在 GitHub 上可用https://github.com/ning/async-http-client
Now Available at GitHub https://github.com/ning/async-http-client
这篇关于Java 异步 HTTP 客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!