異步HTTP和WebSocket的Java客戶端:Async Http Client
異步HTTP和WebSocket的客戶端庫Java類庫。允許Java應用程序輕松地執行HTTP請求并異步處理HTTP響應。該庫還支持WebSocket協議。Async Http Client使用簡單。
import com.ning.http.client.*; import java.util.concurrent.Future;AsyncHttpClient c = new AsyncHttpClient(); Future<String> f = c.prepareGet(" AsyncHandler<String>() { private ByteArrayOutputStream bytes = new ByteArrayOutputStream();
@Override public STATE onStatusReceived(HttpResponseStatus status) throws Exception { int statusCode = status.getStatusCode(); // The Status have been read // If you don't want to read the headers,body or stop processing the response if (statusCode >= 500) { return STATE.ABORT; } } @Override public STATE onHeadersReceived(HttpResponseHeaders h) throws Exception { Headers headers = h.getHeaders(); // The headers have been read // If you don't want to read the body, or stop processing the response return STATE.ABORT; } @Override public STATE onBodyPartReceived(HttpResponseBodyPart bodyPart) throws Exception { bytes.write(bodyPart.getBodyPartBytes()); return STATE.CONTINUE; } @Override public String onCompleted() throws Exception { // Will be invoked once the response has been fully read or a ResponseComplete exception // has been thrown. // NOTE: should probably use Content-Encoding from headers return bytes.toString("UTF-8"); } @Override public void onThrowable(Throwable t) { }
});
String bodyResponse = f.get();</pre>
本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!