use of org.apache.http.entity.InputStreamEntity in project okhttp by square.
the class OkApacheClientTest method postInputStreamEntity.
@Test
public void postInputStreamEntity() throws Exception {
server.enqueue(new MockResponse());
final HttpPost post = new HttpPost(server.url("/").url().toURI());
byte[] body = "Hello, world!".getBytes(UTF_8);
post.setEntity(new InputStreamEntity(new ByteArrayInputStream(body), body.length));
client.execute(post);
RecordedRequest request = server.takeRequest();
assertEquals("Hello, world!", request.getBody().readUtf8());
assertEquals(request.getHeader("Content-Length"), "13");
}
use of org.apache.http.entity.InputStreamEntity in project hadoop by apache.
the class AuthenticatorTestCase method _testAuthenticationHttpClient.
protected void _testAuthenticationHttpClient(Authenticator authenticator, boolean doPost) throws Exception {
start();
try {
HttpClient httpClient = getHttpClient();
doHttpClientRequest(httpClient, new HttpGet(getBaseURL()));
// Always do a GET before POST to trigger the SPNego negotiation
if (doPost) {
HttpPost post = new HttpPost(getBaseURL());
byte[] postBytes = POST.getBytes();
ByteArrayInputStream bis = new ByteArrayInputStream(postBytes);
InputStreamEntity entity = new InputStreamEntity(bis, postBytes.length);
// Important that the entity is not repeatable -- this means if
// we have to renegotiate (e.g. b/c the cookie wasn't handled properly)
// the test will fail.
Assert.assertFalse(entity.isRepeatable());
post.setEntity(entity);
doHttpClientRequest(httpClient, post);
}
} finally {
stop();
}
}
use of org.apache.http.entity.InputStreamEntity in project openstack4j by ContainX.
the class HttpCommand method execute.
/**
* Executes the command and returns the Response
*
* @return the response
* @throws Exception
*/
public CloseableHttpResponse execute() throws Exception {
EntityBuilder builder = null;
if (request.getEntity() != null) {
if (InputStream.class.isAssignableFrom(request.getEntity().getClass())) {
InputStreamEntity ise = new InputStreamEntity((InputStream) request.getEntity(), ContentType.create(request.getContentType()));
((HttpEntityEnclosingRequestBase) clientReq).setEntity(ise);
} else {
builder = EntityBuilder.create().setContentType(ContentType.create(request.getContentType(), "UTF-8")).setText(ObjectMapperSingleton.getContext(request.getEntity().getClass()).writer().writeValueAsString(request.getEntity()));
}
} else if (request.hasJson()) {
builder = EntityBuilder.create().setContentType(ContentType.APPLICATION_JSON).setText(request.getJson());
}
if (builder != null && clientReq instanceof HttpEntityEnclosingRequestBase)
((HttpEntityEnclosingRequestBase) clientReq).setEntity(builder.build());
return client.execute(clientReq);
}
use of org.apache.http.entity.InputStreamEntity in project camel by apache.
the class Olingo2AppImpl method writeContent.
private <T> void writeContent(final Edm edm, HttpEntityEnclosingRequestBase httpEntityRequest, final UriInfoWithType uriInfo, final Object content, final Olingo2ResponseHandler<T> responseHandler) {
try {
// process resource by UriType
final ODataResponse response = writeContent(edm, uriInfo, content);
// copy all response headers
for (String header : response.getHeaderNames()) {
httpEntityRequest.setHeader(header, response.getHeader(header));
}
// get (http) entity which is for default Olingo2 implementation an InputStream
if (response.getEntity() instanceof InputStream) {
httpEntityRequest.setEntity(new InputStreamEntity((InputStream) response.getEntity()));
/*
// avoid sending it without a header field set
if (!httpEntityRequest.containsHeader(HttpHeaders.CONTENT_TYPE)) {
httpEntityRequest.addHeader(HttpHeaders.CONTENT_TYPE, getContentType());
}
*/
}
// execute HTTP request
final Header requestContentTypeHeader = httpEntityRequest.getFirstHeader(HttpHeaders.CONTENT_TYPE);
final ContentType requestContentType = requestContentTypeHeader != null ? ContentType.parse(requestContentTypeHeader.getValue()) : contentType;
execute(httpEntityRequest, requestContentType, new AbstractFutureCallback<T>(responseHandler) {
@SuppressWarnings("unchecked")
@Override
public void onCompleted(HttpResponse result) throws IOException, EntityProviderException, BatchException, ODataApplicationException {
// if a entity is created (via POST request) the response body contains the new created entity
HttpStatusCodes statusCode = HttpStatusCodes.fromStatusCode(result.getStatusLine().getStatusCode());
// look for no content, or no response body!!!
final boolean noEntity = result.getEntity() == null || result.getEntity().getContentLength() == 0;
if (statusCode == HttpStatusCodes.NO_CONTENT || noEntity) {
responseHandler.onResponse((T) HttpStatusCodes.fromStatusCode(result.getStatusLine().getStatusCode()));
} else {
switch(uriInfo.getUriType()) {
case URI9:
// $batch
final List<BatchSingleResponse> singleResponses = EntityProvider.parseBatchResponse(result.getEntity().getContent(), result.getFirstHeader(HttpHeaders.CONTENT_TYPE).getValue());
// parse batch response bodies
final List<Olingo2BatchResponse> responses = new ArrayList<Olingo2BatchResponse>();
Map<String, String> contentIdLocationMap = new HashMap<String, String>();
final List<Olingo2BatchRequest> batchRequests = (List<Olingo2BatchRequest>) content;
final Iterator<Olingo2BatchRequest> iterator = batchRequests.iterator();
for (BatchSingleResponse response : singleResponses) {
final Olingo2BatchRequest request = iterator.next();
if (request instanceof Olingo2BatchChangeRequest && ((Olingo2BatchChangeRequest) request).getContentId() != null) {
contentIdLocationMap.put("$" + ((Olingo2BatchChangeRequest) request).getContentId(), response.getHeader(HttpHeaders.LOCATION));
}
try {
responses.add(parseResponse(edm, contentIdLocationMap, request, response));
} catch (Exception e) {
// report any parsing errors as error response
responses.add(new Olingo2BatchResponse(Integer.parseInt(response.getStatusCode()), response.getStatusInfo(), response.getContentId(), response.getHeaders(), new ODataApplicationException("Error parsing response for " + request + ": " + e.getMessage(), Locale.ENGLISH, e)));
}
}
responseHandler.onResponse((T) responses);
break;
case URI4:
case URI5:
// simple property
// get the response content as Object for $value or Map<String, Object> otherwise
final List<EdmProperty> simplePropertyPath = uriInfo.getPropertyPath();
final EdmProperty simpleProperty = simplePropertyPath.get(simplePropertyPath.size() - 1);
if (uriInfo.isValue()) {
responseHandler.onResponse((T) EntityProvider.readPropertyValue(simpleProperty, result.getEntity().getContent()));
} else {
responseHandler.onResponse((T) EntityProvider.readProperty(getContentType(), simpleProperty, result.getEntity().getContent(), EntityProviderReadProperties.init().build()));
}
break;
case URI3:
// complex property
// get the response content as Map<String, Object>
final List<EdmProperty> complexPropertyPath = uriInfo.getPropertyPath();
final EdmProperty complexProperty = complexPropertyPath.get(complexPropertyPath.size() - 1);
responseHandler.onResponse((T) EntityProvider.readProperty(getContentType(), complexProperty, result.getEntity().getContent(), EntityProviderReadProperties.init().build()));
break;
case URI7A:
// $links with 0..1 cardinality property
// get the response content as String
final EdmEntitySet targetLinkEntitySet = uriInfo.getTargetEntitySet();
responseHandler.onResponse((T) EntityProvider.readLink(getContentType(), targetLinkEntitySet, result.getEntity().getContent()));
break;
case URI7B:
// $links with * cardinality property
// get the response content as java.util.List<String>
final EdmEntitySet targetLinksEntitySet = uriInfo.getTargetEntitySet();
responseHandler.onResponse((T) EntityProvider.readLinks(getContentType(), targetLinksEntitySet, result.getEntity().getContent()));
break;
case URI1:
case URI2:
case URI6A:
case URI6B:
// Entity
// get the response content as an ODataEntry object
responseHandler.onResponse((T) EntityProvider.readEntry(response.getContentHeader(), uriInfo.getTargetEntitySet(), result.getEntity().getContent(), EntityProviderReadProperties.init().build()));
break;
default:
throw new ODataApplicationException("Unsupported resource type " + uriInfo.getTargetType(), Locale.ENGLISH);
}
}
}
});
} catch (ODataException e) {
responseHandler.onException(e);
} catch (URISyntaxException e) {
responseHandler.onException(e);
} catch (UnsupportedEncodingException e) {
responseHandler.onException(e);
} catch (IOException e) {
responseHandler.onException(e);
}
}
use of org.apache.http.entity.InputStreamEntity in project lucene-solr by apache.
the class HttpSolrClient method createMethod.
protected HttpRequestBase createMethod(final SolrRequest request, String collection) throws IOException, SolrServerException {
SolrParams params = request.getParams();
Collection<ContentStream> streams = requestWriter.getContentStreams(request);
String path = requestWriter.getPath(request);
if (path == null || !path.startsWith("/")) {
path = DEFAULT_PATH;
}
ResponseParser parser = request.getResponseParser();
if (parser == null) {
parser = this.parser;
}
// The parser 'wt=' and 'version=' params are used instead of the original
// params
ModifiableSolrParams wparams = new ModifiableSolrParams(params);
if (parser != null) {
wparams.set(CommonParams.WT, parser.getWriterType());
wparams.set(CommonParams.VERSION, parser.getVersion());
}
if (invariantParams != null) {
wparams.add(invariantParams);
}
String basePath = baseUrl;
if (collection != null)
basePath += "/" + collection;
if (request instanceof V2Request) {
if (System.getProperty("solr.v2RealPath") == null) {
basePath = baseUrl.replace("/solr", "/v2");
} else {
basePath = baseUrl + "/____v2";
}
}
if (SolrRequest.METHOD.GET == request.getMethod()) {
if (streams != null) {
throw new SolrException(SolrException.ErrorCode.BAD_REQUEST, "GET can't send streams!");
}
return new HttpGet(basePath + path + wparams.toQueryString());
}
if (SolrRequest.METHOD.DELETE == request.getMethod()) {
return new HttpDelete(basePath + path + wparams.toQueryString());
}
if (SolrRequest.METHOD.POST == request.getMethod() || SolrRequest.METHOD.PUT == request.getMethod()) {
String url = basePath + path;
boolean hasNullStreamName = false;
if (streams != null) {
for (ContentStream cs : streams) {
if (cs.getName() == null) {
hasNullStreamName = true;
break;
}
}
}
boolean isMultipart = ((this.useMultiPartPost && SolrRequest.METHOD.POST == request.getMethod()) || (streams != null && streams.size() > 1)) && !hasNullStreamName;
LinkedList<NameValuePair> postOrPutParams = new LinkedList<>();
if (streams == null || isMultipart) {
// send server list and request list as query string params
ModifiableSolrParams queryParams = calculateQueryParams(this.queryParams, wparams);
queryParams.add(calculateQueryParams(request.getQueryParams(), wparams));
String fullQueryUrl = url + queryParams.toQueryString();
HttpEntityEnclosingRequestBase postOrPut = SolrRequest.METHOD.POST == request.getMethod() ? new HttpPost(fullQueryUrl) : new HttpPut(fullQueryUrl);
if (!isMultipart) {
postOrPut.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
}
List<FormBodyPart> parts = new LinkedList<>();
Iterator<String> iter = wparams.getParameterNamesIterator();
while (iter.hasNext()) {
String p = iter.next();
String[] vals = wparams.getParams(p);
if (vals != null) {
for (String v : vals) {
if (isMultipart) {
parts.add(new FormBodyPart(p, new StringBody(v, StandardCharsets.UTF_8)));
} else {
postOrPutParams.add(new BasicNameValuePair(p, v));
}
}
}
}
// TODO: remove deprecated - first simple attempt failed, see {@link MultipartEntityBuilder}
if (isMultipart && streams != null) {
for (ContentStream content : streams) {
String contentType = content.getContentType();
if (contentType == null) {
// default
contentType = BinaryResponseParser.BINARY_CONTENT_TYPE;
}
String name = content.getName();
if (name == null) {
name = "";
}
parts.add(new FormBodyPart(name, new InputStreamBody(content.getStream(), contentType, content.getName())));
}
}
if (parts.size() > 0) {
MultipartEntity entity = new MultipartEntity(HttpMultipartMode.STRICT);
for (FormBodyPart p : parts) {
entity.addPart(p);
}
postOrPut.setEntity(entity);
} else {
//not using multipart
postOrPut.setEntity(new UrlEncodedFormEntity(postOrPutParams, StandardCharsets.UTF_8));
}
return postOrPut;
} else // It is has one stream, it is the post body, put the params in the URL
{
String fullQueryUrl = url + wparams.toQueryString();
HttpEntityEnclosingRequestBase postOrPut = SolrRequest.METHOD.POST == request.getMethod() ? new HttpPost(fullQueryUrl) : new HttpPut(fullQueryUrl);
// Single stream as body
// Using a loop just to get the first one
final ContentStream[] contentStream = new ContentStream[1];
for (ContentStream content : streams) {
contentStream[0] = content;
break;
}
if (contentStream[0] instanceof RequestWriter.LazyContentStream) {
Long size = contentStream[0].getSize();
postOrPut.setEntity(new InputStreamEntity(contentStream[0].getStream(), size == null ? -1 : size) {
@Override
public Header getContentType() {
return new BasicHeader("Content-Type", contentStream[0].getContentType());
}
@Override
public boolean isRepeatable() {
return false;
}
});
} else {
Long size = contentStream[0].getSize();
postOrPut.setEntity(new InputStreamEntity(contentStream[0].getStream(), size == null ? -1 : size) {
@Override
public Header getContentType() {
return new BasicHeader("Content-Type", contentStream[0].getContentType());
}
@Override
public boolean isRepeatable() {
return false;
}
});
}
return postOrPut;
}
}
throw new SolrServerException("Unsupported method: " + request.getMethod());
}
Aggregations