下面列出了怎么用org.apache.http.impl.DefaultHttpResponseFactory的API类实例代码及写法,或者点击链接到github查看源代码。
protected HttpServerConnectionUpnpStream(ProtocolFactory protocolFactory,
HttpServerConnection connection,
final HttpParams params) {
super(protocolFactory);
this.connection = connection;
this.params = params;
// The Date header is recommended in UDA, need to document the requirement in StreamServer interface?
httpProcessor.addInterceptor(new ResponseDate());
// The Server header is only required for Control so callers have to add it to UPnPMessage
// httpProcessor.addInterceptor(new ResponseServer());
httpProcessor.addInterceptor(new ResponseContent());
httpProcessor.addInterceptor(new ResponseConnControl());
httpService =
new UpnpHttpService(
httpProcessor,
new DefaultConnectionReuseStrategy(),
new DefaultHttpResponseFactory()
);
httpService.setParams(params);
}
protected HttpServerConnectionUpnpStream(ProtocolFactory protocolFactory,
HttpServerConnection connection,
final HttpParams params) {
super(protocolFactory);
this.connection = connection;
this.params = params;
// The Date header is recommended in UDA, need to document the requirement in StreamServer interface?
httpProcessor.addInterceptor(new ResponseDate());
// The Server header is only required for Control so callers have to add it to UPnPMessage
// httpProcessor.addInterceptor(new ResponseServer());
httpProcessor.addInterceptor(new ResponseContent());
httpProcessor.addInterceptor(new ResponseConnControl());
httpService =
new UpnpHttpService(
httpProcessor,
new DefaultConnectionReuseStrategy(),
new DefaultHttpResponseFactory()
);
httpService.setParams(params);
}
public HttpResponse put(Map<String, InputStream> uriAndStreamMap, Map<String, String> headers) throws MultipleBintrayCallException {
List<Future<String>> executions = new ArrayList<>();
List<BintrayCallException> errors = new ArrayList<>();
List<RequestRunner> runners = createPutRequestRunners(uriAndStreamMap, headers, errors);
try {
executions = executorService.invokeAll(runners);
} catch (InterruptedException e) {
BintrayCallException bce = new BintrayCallException(409, e.getMessage(), (e.getCause() == null) ? ""
: e.getCause().toString() + " : " + e.getCause().getMessage());
log.error(bce.toString());
log.debug("{}", e.getMessage(), e);
errors.add(bce);
}
collectResults(executions, errors);
//Return ok or throw errors
if (errors.isEmpty()) {
String entity = "Operation Successful";
HttpResponse response = DefaultHttpResponseFactory.INSTANCE.newHttpResponse(
new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_CREATED, new HttpClientContext());
response.setEntity(new StringEntity(entity, Charset.forName("UTF-8")));
return response;
} else {
throw new MultipleBintrayCallException(errors);
}
}
public ListenerThread(final ApiServer requestHandler, final int port) {
try {
_serverSocket = new ServerSocket(port);
} catch (final IOException ioex) {
s_logger.error("error initializing api server", ioex);
return;
}
_params = new BasicHttpParams();
_params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");
// Set up the HTTP protocol processor
final BasicHttpProcessor httpproc = new BasicHttpProcessor();
httpproc.addInterceptor(new ResponseDate());
httpproc.addInterceptor(new ResponseServer());
httpproc.addInterceptor(new ResponseContent());
httpproc.addInterceptor(new ResponseConnControl());
// Set up request handlers
final HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
reqistry.register("*", requestHandler);
// Set up the HTTP service
_httpService = new HttpService(httpproc, new NoConnectionReuseStrategy(), new DefaultHttpResponseFactory());
_httpService.setParams(_params);
_httpService.setHandlerResolver(reqistry);
}
public ListenerThread(final HttpRequestHandler requestHandler, final int port) {
_executor = Executors.newCachedThreadPool(new NamedThreadFactory("Cluster-Listener"));
try {
_serverSocket = new ServerSocket(port);
} catch (final IOException ioex) {
s_logger.error("error initializing cluster service servlet container", ioex);
return;
}
_params = new BasicHttpParams();
_params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");
// Set up the HTTP protocol processor
final BasicHttpProcessor httpproc = new BasicHttpProcessor();
httpproc.addInterceptor(new ResponseDate());
httpproc.addInterceptor(new ResponseServer());
httpproc.addInterceptor(new ResponseContent());
httpproc.addInterceptor(new ResponseConnControl());
// Set up request handlers
final HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
reqistry.register("/clusterservice", requestHandler);
// Set up the HTTP service
_httpService = new HttpService(httpproc, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory());
_httpService.setParams(_params);
_httpService.setHandlerResolver(reqistry);
}
private static ManagedHttpClientConnectionFactory createConnectionFactory() {
return new ManagedHttpClientConnectionFactory(null, (buffer, constraints) ->
new GarbageAllergicHttpResponseParser(
buffer,
IcyHttpLineParser.ICY_INSTANCE,
DefaultHttpResponseFactory.INSTANCE,
constraints
));
}
private AsyncRequestWrapperImpl createAsyncRequestWrapperImplWithRetryAfter(int retryAfter)
throws IOException, URISyntaxException {
HttpClient httpClient = mock(HttpClient.class);
ODataClient oDataClient = mock(ODataClient.class);
Configuration configuration = mock(Configuration.class);
HttpClientFactory httpClientFactory = mock(HttpClientFactory.class);
HttpUriRequestFactory httpUriRequestFactory = mock(HttpUriRequestFactory.class);
HttpUriRequest httpUriRequest = mock(HttpUriRequest.class);
when(oDataClient.getConfiguration()).thenReturn(configuration);
when(configuration.getHttpClientFactory()).thenReturn(httpClientFactory);
when(configuration.getHttpUriRequestFactory()).thenReturn(httpUriRequestFactory);
when(httpClientFactory.create(any(), any())).thenReturn(httpClient);
when(httpUriRequestFactory.create(any(), any())).thenReturn(httpUriRequest);
HttpResponseFactory factory = new DefaultHttpResponseFactory();
HttpResponse firstResponse = factory.newHttpResponse(
new BasicStatusLine(HttpVersion.HTTP_1_1, 202, null), null);
firstResponse.addHeader(HttpHeader.LOCATION, "http://localhost/monitor");
firstResponse.addHeader(HttpHeader.RETRY_AFTER, String.valueOf(retryAfter));
when(httpClient.execute(any(HttpUriRequest.class))).thenReturn(firstResponse);
AbstractODataRequest oDataRequest = mock(AbstractODataRequest.class);
ODataResponse oDataResponse = mock(ODataResponse.class);
when(oDataRequest.getResponseTemplate()).thenReturn(oDataResponse);
when(oDataRequest.getURI()).thenReturn(new URI("http://localhost/path"));
when(oDataResponse.initFromHttpResponse(any(HttpResponse.class))).thenReturn(null);
return new AsyncRequestWrapperImpl(oDataClient, oDataRequest);
}
private AsyncResponseWrapperImpl createAsyncRequestWrapperImplWithLocation(String target, String location)
throws IOException, URISyntaxException {
HttpClient httpClient = mock(HttpClient.class);
ODataClient oDataClient = mock(ODataClient.class);
Configuration configuration = mock(Configuration.class);
HttpClientFactory httpClientFactory = mock(HttpClientFactory.class);
HttpUriRequestFactory httpUriRequestFactory = mock(HttpUriRequestFactory.class);
HttpUriRequest httpUriRequest = mock(HttpUriRequest.class);
when(oDataClient.getConfiguration()).thenReturn(configuration);
when(configuration.getHttpClientFactory()).thenReturn(httpClientFactory);
when(configuration.getHttpUriRequestFactory()).thenReturn(httpUriRequestFactory);
when(httpClientFactory.create(any(), any())).thenReturn(httpClient);
when(httpUriRequestFactory.create(any(), any())).thenReturn(httpUriRequest);
HttpResponseFactory factory = new DefaultHttpResponseFactory();
HttpResponse firstResponse = factory.newHttpResponse(
new BasicStatusLine(HttpVersion.HTTP_1_1, 202, null), null);
firstResponse.addHeader(HttpHeader.LOCATION, location);
when(httpClient.execute(any(HttpUriRequest.class))).thenReturn(firstResponse);
ODataResponse oDataResponse = mock(ODataResponse.class);
when(oDataResponse.initFromHttpResponse(any(HttpResponse.class))).thenReturn(null);
AbstractODataRequest oDataRequest = mock(AbstractODataRequest.class);
when(oDataRequest.getURI()).thenReturn(new URI(target));
when(oDataRequest.getResponseTemplate()).thenReturn(oDataResponse);
AsyncRequestWrapperImpl req = new AsyncRequestWrapperImpl(oDataClient, oDataRequest);
AsyncResponseWrapper wrappedResponse = req.execute();
assertTrue(wrappedResponse instanceof AsyncResponseWrapperImpl);
return (AsyncResponseWrapperImpl) wrappedResponse;
}
public ListenerThread(final ApiServer requestHandler, final int port) {
try {
_serverSocket = new ServerSocket(port);
} catch (final IOException ioex) {
s_logger.error("error initializing api server", ioex);
return;
}
_params = new BasicHttpParams();
_params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");
// Set up the HTTP protocol processor
final BasicHttpProcessor httpproc = new BasicHttpProcessor();
httpproc.addInterceptor(new ResponseDate());
httpproc.addInterceptor(new ResponseServer());
httpproc.addInterceptor(new ResponseContent());
httpproc.addInterceptor(new ResponseConnControl());
// Set up request handlers
final HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
reqistry.register("*", requestHandler);
// Set up the HTTP service
_httpService = new HttpService(httpproc, new NoConnectionReuseStrategy(), new DefaultHttpResponseFactory());
_httpService.setParams(_params);
_httpService.setHandlerResolver(reqistry);
}
public ListenerThread(HttpRequestHandler requestHandler, int port) {
_executor = Executors.newCachedThreadPool(new NamedThreadFactory("Cluster-Listener"));
try {
_serverSocket = new ServerSocket(port);
} catch (IOException ioex) {
s_logger.error("error initializing cluster service servlet container", ioex);
return;
}
_params = new BasicHttpParams();
_params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");
// Set up the HTTP protocol processor
BasicHttpProcessor httpproc = new BasicHttpProcessor();
httpproc.addInterceptor(new ResponseDate());
httpproc.addInterceptor(new ResponseServer());
httpproc.addInterceptor(new ResponseContent());
httpproc.addInterceptor(new ResponseConnControl());
// Set up request handlers
HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
reqistry.register("/clusterservice", requestHandler);
// Set up the HTTP service
_httpService = new HttpService(httpproc, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory());
_httpService.setParams(_params);
_httpService.setHandlerResolver(reqistry);
}
/**
* Executes a sign request using the ExecutorService and uses the file count to set a timeout to avoid timing out
* on long requests
*
* @throws BintrayCallException
*/
public HttpResponse sign(String uri, Map<String, String> headers, int fileCount) throws BintrayCallException {
HttpPost signRequest = new HttpPost(createUrl(uri));
setHeaders(signRequest, headers);
signRequest.setConfig(RequestConfig.custom().setSocketTimeout(signRequestTimeoutPerFile * fileCount)
.setConnectionRequestTimeout(signRequestTimeoutPerFile * fileCount)
.setConnectTimeout(signRequestTimeoutPerFile * fileCount).build());
RequestRunner runner = new RequestRunner(signRequest, client, responseHandler);
Future<String> signResponse = executorService.submit(runner);
try {
signResponse.get();
} catch (Exception e) {
BintrayCallException bce;
if (e.getCause() instanceof BintrayCallException) {
bce = (BintrayCallException) e.getCause();
} else {
bce = new BintrayCallException(409, e.getMessage(), (e.getCause() == null) ? ""
: ", " + e.getCause().toString() + " : " + e.getCause().getMessage());
}
log.error(bce.toString());
log.debug("{}", e.getMessage(), e);
throw bce;
}
//Return ok
String entity = "Signing the version was successful";
HttpResponse response = DefaultHttpResponseFactory.INSTANCE.newHttpResponse(
new ProtocolVersion("HTTP", 1, 1), HttpStatus.SC_CREATED, new HttpClientContext());
response.setEntity(new StringEntity(entity, Charset.forName("UTF-8")));
return response;
}
@Override
public HttpResponse handleResponse(HttpResponse response) throws BintrayCallException {
int statusCode = response.getStatusLine().getStatusCode();
if (statusNotOk(statusCode)) {
BintrayCallException bce = new BintrayCallException(response);
//We're using CloseableHttpClient so it's ok
HttpClientUtils.closeQuietly((CloseableHttpResponse) response);
throw bce;
}
//Response entity might be null, 500 and 405 also give the html itself so skip it
byte[] entity = new byte[0];
if (response.getEntity() != null && statusCode != 500 && statusCode != 405) {
try {
entity = IOUtils.toByteArray(response.getEntity().getContent());
} catch (IOException | NullPointerException e) {
//Null entity - Ignore
} finally {
HttpClientUtils.closeQuietly((CloseableHttpResponse) response);
}
}
HttpResponse newResponse = DefaultHttpResponseFactory.INSTANCE.newHttpResponse(response.getStatusLine(),
new HttpClientContext());
newResponse.setEntity(new ByteArrayEntity(entity));
newResponse.setHeaders(response.getAllHeaders());
return newResponse;
}
protected RequestListener() throws Exception {
mHttpService = new org.apache.http.protocol.HttpService(
mHttpProcessor,
new DefaultConnectionReuseStrategy(),
new DefaultHttpResponseFactory());
mHttpService.setHandlerResolver(mRegistry);
mHttpService.setParams(mParams);
}
public HttpResponseFactory newResponseFactory() {
return new DefaultHttpResponseFactory();
}
private DropboxServerException notFoundException() {
HttpResponseFactory factory = new DefaultHttpResponseFactory();
HttpResponse response = factory.newHttpResponse(new BasicStatusLine(
HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_FOUND, null), null);
return new DropboxServerException(response);
}
private DropboxServerException notFoundException() {
HttpResponseFactory factory = new DefaultHttpResponseFactory();
HttpResponse response = factory.newHttpResponse(new BasicStatusLine(
HttpVersion.HTTP_1_1, HttpStatus.SC_NOT_FOUND, null), null);
return new DropboxServerException(response);
}