Created
February 24, 2011 17:03
-
-
Save rschildmeijer/842452 to your computer and use it in GitHub Desktop.
AsynchronousHttpClient
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.deftserver.web.http.client; | |
import java.io.IOException; | |
import java.net.URL; | |
import java.nio.channels.SocketChannel; | |
import org.deftserver.io.AsynchronousSocket; | |
import org.deftserver.web.AsyncCallback; | |
import org.deftserver.web.AsyncResult; | |
import org.slf4j.Logger; | |
import org.slf4j.LoggerFactory; | |
public class AsynchronousHttpClient { | |
private static final Logger logger = LoggerFactory.getLogger(AsynchronousHttpClient.class); | |
private AsynchronousSocket socket; | |
public AsynchronousHttpClient() { | |
try { | |
socket = new AsynchronousSocket(SocketChannel.open().configureBlocking(false)); | |
} catch (IOException e) { | |
logger.error("Error opening SocketChannel: {}" + e.getMessage()); | |
} | |
} | |
public void fetch(URL url, AsyncResult<HttpResponse> cb) { | |
socket.connect( | |
url.getHost(), | |
url.getPort(), | |
new AsyncCallback() { @Override public void onCallback() { onConnect(); }} | |
); | |
// TODO start a timer, if timeout => return "failure" to the client using the AHC else cancel timeout | |
} | |
public void close() { | |
socket.close(); | |
} | |
private void onConnect() { | |
logger.debug("Connected..."); | |
socket.write( | |
"GET / HTTP/1.0\r\nFrom: someuser@jmarshall.com\r\nUser-Agent: HTTPTool/1.0\r\n\r\n", | |
new AsyncCallback() { @Override public void onCallback() { onWriteComplete(); }} | |
); | |
} | |
private void onWriteComplete() { | |
logger.debug("onWriteComplete..."); | |
socket.readUntil( | |
"\r\n", | |
new NaiveAsyncResult() { @Override public void onSuccess(String result) { onHeaders(result); } | |
}); | |
} | |
private void onHeaders(String headers) { | |
logger.debug("result: {}", headers); | |
// TODO read the rest of the body | |
} | |
/** | |
* Naive because all it does when an exception is thrown is log the exception. | |
*/ | |
private static abstract class NaiveAsyncResult implements AsyncResult<String> { | |
@Override | |
public void onFailure(Throwable caught) { | |
logger.debug("onFailure: {}", caught); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment