List of usage examples for org.apache.http.client.methods HttpEntityEnclosingRequestBase setEntity
public void setEntity(final HttpEntity entity)
From source file:uk.co.tfd.sm.proxy.ProxyClientServiceImpl.java
/** * Executes a HTTP call using a path in the JCR to point to a template and a * map of properties to populate that template with. An example might be a * SOAP call./*from w w w. j a v a2s. com*/ * * <pre> * {http://www.w3.org/2001/12/soap-envelope}Envelope:{ * {http://www.w3.org/2001/12/soap-envelope}Body:{ * {http://www.example.org/stock}GetStockPriceResponse:{ * >body:[ ] * {http://www.example.org/stock}Price:{ * >body:[34.5] * } * } * >body:[ ] * } * >body:[ ] * {http://www.w3.org/2001/12/soap-envelope}encodingStyle:[http://www.w3.org/2001/12/soap-encoding] * } * * </pre> * * @param resource * the resource containing the proxy end point specification. * @param headers * a map of headers to set int the request. * @param input * a map of parameters for all templates (both url and body) * @param requestInputStream * containing the request body (can be null if the call requires * no body or the template will be used to generate the body) * @param requestContentLength * if the requestImputStream is specified, the length specifies * the lenght of the body. * @param requerstContentType * the content type of the request, if null the node property * sakai:proxy-request-content-type will be used. * @throws ProxyClientException */ public ProxyResponse executeCall(Map<String, Object> config, Map<String, Object> headers, Map<String, Object> input, InputStream requestInputStream, long requestContentLength, String requestContentType) throws ProxyClientException { try { LOGGER.info( "Calling Execute Call with Config:[{}] Headers:[{}] Input:[{}] " + "RequestInputStream:[{}] InputStreamContentLength:[{}] RequestContentType:[{}] ", new Object[] { config, headers, input, requestInputStream, requestContentLength, requestContentType }); bindConfig(config); if (config != null && config.containsKey(CONFIG_REQUEST_PROXY_ENDPOINT)) { // setup the post request String endpointURL = (String) config.get(CONFIG_REQUEST_PROXY_ENDPOINT); if (isUnsafeProxyDefinition(config)) { try { URL u = new URL(endpointURL); String host = u.getHost(); if (host.indexOf('$') >= 0) { throw new ProxyClientException( "Invalid Endpoint template, relies on request to resolve valid URL " + u); } } catch (MalformedURLException e) { throw new ProxyClientException( "Invalid Endpoint template, relies on request to resolve valid URL", e); } } LOGGER.info("Valied Endpoint Def"); Map<String, Object> context = Maps.newHashMap(input); // add in the config properties from the bundle overwriting // everything else. context.put("config", configProperties); endpointURL = processUrlTemplate(endpointURL, context); LOGGER.info("Calling URL {} ", endpointURL); ProxyMethod proxyMethod = ProxyMethod.GET; if (config.containsKey(CONFIG_REQUEST_PROXY_METHOD)) { try { proxyMethod = ProxyMethod.valueOf((String) config.get(CONFIG_REQUEST_PROXY_METHOD)); } catch (Exception e) { } } HttpClient client = getHttpClient(); HttpUriRequest method = null; switch (proxyMethod) { case GET: if (config.containsKey(CONFIG_LIMIT_GET_SIZE)) { long maxSize = (Long) config.get(CONFIG_LIMIT_GET_SIZE); HttpHead h = new HttpHead(endpointURL); HttpParams params = h.getParams(); // make certain we reject the body of a head params.setBooleanParameter("http.protocol.reject-head-body", true); h.setParams(params); populateMessage(method, config, headers); HttpResponse response = client.execute(h); if (response.getStatusLine().getStatusCode() == 200) { // Check if the content-length is smaller than the // maximum (if any). Header contentLengthHeader = response.getLastHeader("Content-Length"); if (contentLengthHeader != null) { long length = Long.parseLong(contentLengthHeader.getValue()); if (length > maxSize) { return new ProxyResponseImpl(HttpServletResponse.SC_PRECONDITION_FAILED, "Response too large", response); } } } else { return new ProxyResponseImpl(response); } } method = new HttpGet(endpointURL); break; case HEAD: method = new HttpHead(endpointURL); break; case OPTIONS: method = new HttpOptions(endpointURL); break; case POST: method = new HttpPost(endpointURL); break; case PUT: method = new HttpPut(endpointURL); break; default: method = new HttpGet(endpointURL); } populateMessage(method, config, headers); if (requestInputStream == null && !config.containsKey(CONFIG_PROXY_REQUEST_TEMPLATE)) { if (method instanceof HttpPost) { HttpPost postMethod = (HttpPost) method; MultipartEntity multipart = new MultipartEntity(); for (Entry<String, Object> param : input.entrySet()) { String key = param.getKey(); Object value = param.getValue(); if (value instanceof Object[]) { for (Object val : (Object[]) value) { addPart(multipart, key, val); } } else { addPart(multipart, key, value); } postMethod.setEntity(multipart); } } } else { if (method instanceof HttpEntityEnclosingRequestBase) { String contentType = requestContentType; if (contentType == null && config.containsKey(CONFIG_REQUEST_CONTENT_TYPE)) { contentType = (String) config.get(CONFIG_REQUEST_CONTENT_TYPE); } if (contentType == null) { contentType = APPLICATION_OCTET_STREAM; } HttpEntityEnclosingRequestBase eemethod = (HttpEntityEnclosingRequestBase) method; if (requestInputStream != null) { eemethod.setHeader(HttpHeaders.CONTENT_TYPE, contentType); eemethod.setEntity(new InputStreamEntity(requestInputStream, requestContentLength)); } else { // build the request StringWriter body = new StringWriter(); templateService.evaluate(context, body, (String) config.get("path"), (String) config.get(CONFIG_PROXY_REQUEST_TEMPLATE)); byte[] soapBodyContent = body.toString().getBytes("UTF-8"); eemethod.setHeader(HttpHeaders.CONTENT_TYPE, contentType); eemethod.setEntity(new InputStreamEntity(new ByteArrayInputStream(soapBodyContent), soapBodyContent.length)); } } } HttpResponse response = client.execute(method); if (response.getStatusLine().getStatusCode() == 302 && method instanceof HttpEntityEnclosingRequestBase) { // handle redirects on post and put String url = response.getFirstHeader("Location").getValue(); method = new HttpGet(url); response = client.execute(method); } return new ProxyResponseImpl(response); } } catch (ProxyClientException e) { throw e; } catch (Exception e) { LOGGER.error(e.getMessage(), e); throw new ProxyClientException("The Proxy request specified by " + config + " failed, cause follows:", e); } finally { unbindConfig(); } throw new ProxyClientException( "The Proxy request specified by " + config + " does not contain a valid endpoint specification "); }
From source file:co.cask.cdap.internal.app.services.http.AppFabricTestBase.java
protected HttpResponse addArtifactProperties(Id.Artifact artifactId, Map<String, String> properties) throws Exception { String nonNamespacePath = String.format("artifacts/%s/versions/%s/properties", artifactId.getName(), artifactId.getVersion());/*from w w w.j ava 2 s . co m*/ String path = getVersionedAPIPath(nonNamespacePath, artifactId.getNamespace().getId()); HttpEntityEnclosingRequestBase request = getPut(path); request.setEntity(new ByteArrayEntity(properties.toString().getBytes())); return execute(request); }
From source file:com.frand.easyandroid.http.FFHttpClient.java
/** * Perform a HTTP POST request and track the Android Context which initiated * the request. Set headers only for this request * //from w ww. ja va 2s .c o m * @param context * the Android Context which initiated the request. * @param url * the URL to send the request to. * @param headers * set headers only for this request * @param params * additional POST parameters to send with the request. * @param contentType * the content type of the payload you are sending, for example * application/json if sending a json payload. * @param responseHandler * the response handler instance that should handle the response. */ public void post(Context context, int reqTag, String url, Header[] headers, FFRequestParams params, String contentType, FFHttpRespHandler responseHandler) { HttpEntityEnclosingRequestBase request = new HttpPost(url); if (params != null) request.setEntity(paramsToEntity(params)); if (headers != null) request.setHeaders(headers); sendRequest(httpClient, httpContext, request, contentType, responseHandler, context, reqTag, getUrlWithQueryString(url, params)); }
From source file:cloudfoundry.norouter.f5.client.HttpClientIControlClient.java
private JsonNode update(String uri, Object resource, Method method) { try {//from www .ja v a 2s .c om final String body = mapper.writeValueAsString(resource); LOGGER.debug("{}ting {} {}", method, uri, body); final HttpEntityEnclosingRequestBase request; final URI resolvedUri = address.resolve(uri); switch (method) { case PATCH: request = new HttpPatch(resolvedUri); break; case POST: request = new HttpPost(resolvedUri); break; case PUT: request = new HttpPut(resolvedUri); break; default: throw new IllegalStateException("No handler for: " + method); } request.setHeader(HttpHeaders.CONTENT_TYPE, APPLICATION_JSON); request.setEntity(new StringEntity(body, StandardCharsets.UTF_8)); try (final CloseableHttpResponse response = httpClient.execute(request, context.get())) { final StatusLine statusLine = response.getStatusLine(); final String responseBody = StreamUtils.copyToString(response.getEntity().getContent(), StandardCharsets.UTF_8); validateResponse(statusLine.getStatusCode(), statusLine.getReasonPhrase(), responseBody, 200); return mapper.readTree(responseBody); } } catch (IOException e) { throw new IControlException(e); } }
From source file:org.apache.shindig.gadgets.http.BasicHttpFetcher.java
public HttpResponse fetch(org.apache.shindig.gadgets.http.HttpRequest request) throws GadgetException { HttpUriRequest httpMethod = null;/*from w w w. java2 s . c o m*/ Preconditions.checkNotNull(request); final String methodType = request.getMethod(); final org.apache.http.HttpResponse response; final long started = System.currentTimeMillis(); // Break the request Uri to its components: Uri uri = request.getUri(); if (StringUtils.isEmpty(uri.getAuthority())) { throw new GadgetException(GadgetException.Code.INVALID_USER_DATA, "Missing domain name for request: " + uri, HttpServletResponse.SC_BAD_REQUEST); } if (StringUtils.isEmpty(uri.getScheme())) { throw new GadgetException(GadgetException.Code.INVALID_USER_DATA, "Missing schema for request: " + uri, HttpServletResponse.SC_BAD_REQUEST); } String[] hostparts = StringUtils.splitPreserveAllTokens(uri.getAuthority(), ':'); int port = -1; // default port if (hostparts.length > 2) { throw new GadgetException(GadgetException.Code.INVALID_USER_DATA, "Bad host name in request: " + uri.getAuthority(), HttpServletResponse.SC_BAD_REQUEST); } if (hostparts.length == 2) { try { port = Integer.parseInt(hostparts[1]); } catch (NumberFormatException e) { throw new GadgetException(GadgetException.Code.INVALID_USER_DATA, "Bad port number in request: " + uri.getAuthority(), HttpServletResponse.SC_BAD_REQUEST); } } String requestUri = uri.getPath(); // Treat path as / if set as null. if (uri.getPath() == null) { requestUri = "/"; } if (uri.getQuery() != null) { requestUri += '?' + uri.getQuery(); } // Get the http host to connect to. HttpHost host = new HttpHost(hostparts[0], port, uri.getScheme()); try { if ("POST".equals(methodType) || "PUT".equals(methodType)) { HttpEntityEnclosingRequestBase enclosingMethod = ("POST".equals(methodType)) ? new HttpPost(requestUri) : new HttpPut(requestUri); if (request.getPostBodyLength() > 0) { enclosingMethod .setEntity(new InputStreamEntity(request.getPostBody(), request.getPostBodyLength())); } httpMethod = enclosingMethod; } else if ("GET".equals(methodType)) { httpMethod = new HttpGet(requestUri); } else if ("HEAD".equals(methodType)) { httpMethod = new HttpHead(requestUri); } else if ("DELETE".equals(methodType)) { httpMethod = new HttpDelete(requestUri); } for (Map.Entry<String, List<String>> entry : request.getHeaders().entrySet()) { httpMethod.addHeader(entry.getKey(), StringUtils.join(entry.getValue(), ',')); } // Disable following redirects. if (!request.getFollowRedirects()) { httpMethod.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, false); } // HttpClient doesn't handle all cases when breaking url (specifically '_' in domain) // So lets pass it the url parsed: response = FETCHER.execute(host, httpMethod); if (response == null) { throw new IOException("Unknown problem with request"); } long now = System.currentTimeMillis(); if (now - started > slowResponseWarning) { slowResponseWarning(request, started, now); } return makeResponse(response); } catch (Exception e) { long now = System.currentTimeMillis(); // Find timeout exceptions, respond accordingly if (TIMEOUT_EXCEPTIONS.contains(e.getClass())) { LOG.info("Timeout for " + request.getUri() + " Exception: " + e.getClass().getName() + " - " + e.getMessage() + " - " + (now - started) + "ms"); return HttpResponse.timeout(); } LOG.log(Level.INFO, "Got Exception fetching " + request.getUri() + " - " + (now - started) + "ms", e); // Separate shindig error from external error throw new GadgetException(GadgetException.Code.INTERNAL_SERVER_ERROR, e, HttpServletResponse.SC_INTERNAL_SERVER_ERROR); } finally { // cleanup any outstanding resources.. if (httpMethod != null) try { httpMethod.abort(); } catch (UnsupportedOperationException e) { // ignore } } }
From source file:com.ksc.http.apache.request.impl.ApacheHttpRequestFactory.java
private HttpRequestBase wrapEntity(Request<?> request, HttpEntityEnclosingRequestBase entityEnclosingRequest, String encodedParams) throws FakeIOException { if (HttpMethodName.POST == request.getHttpMethod()) { /*/* w w w . j ava2s. com*/ * If there isn't any payload content to include in this request, * then try to include the POST parameters in the query body, * otherwise, just use the query string. For all KSC Query services, * the best behavior is putting the params in the request body for * POST requests, but we can't do that for S3. */ if (request.getContent() == null && encodedParams != null) { entityEnclosingRequest.setEntity(ApacheUtils.newStringEntity(encodedParams)); } else { entityEnclosingRequest.setEntity(new RepeatableInputStreamRequestEntity(request)); } } else { /* * We should never reuse the entity of the previous request, since * reading from the buffered entity will bypass reading from the * original request content. And if the content contains InputStream * wrappers that were added for validation-purpose (e.g. * Md5DigestCalculationInputStream), these wrappers would never be * read and updated again after AmazonHttpClient resets it in * preparation for the retry. Eventually, these wrappers would * return incorrect validation result. */ if (request.getContent() != null) { HttpEntity entity = new RepeatableInputStreamRequestEntity(request); if (request.getHeaders().get(HttpHeaders.CONTENT_LENGTH) == null) { entity = ApacheUtils.newBufferedHttpEntity(entity); } entityEnclosingRequest.setEntity(entity); } } return entityEnclosingRequest; }
From source file:org.easyj.http.EasyHttpClient.java
/** * Sets parameters map on actual method implementation for execution. * For GET, TRACE, HEAD, OPTIONS it appends the parameters to que query string. */// ww w.j a va 2 s.c o m protected void setMethodParameters() { if (method instanceof HttpEntityEnclosingRequestBase) { HttpEntityEnclosingRequestBase req = (HttpEntityEnclosingRequestBase) method; try { if (this.entity != null) { req.setEntity(this.entity); } else { req.setEntity(new UrlEncodedFormEntity(prepareParameters(), HTTP.UTF_8)); } } catch (UnsupportedEncodingException ex) { logger.error("Encoding Not Supported while setting entity parameters: ", ex); } } else { setMethodQueryString(toQueryString(parameters)); } }
From source file:com.ibm.watson.developer_cloud.service.Request.java
/** * Builds a request with the given set of parameters and files. * /* ww w.j av a 2s . c om*/ * * @return HTTP request, prepared to be executed * @throws UnsupportedEncodingException */ public HttpRequestBase build() throws UnsupportedEncodingException { // GET method.setURI(URI.create(toUrl())); // POST/PUT if (method instanceof HttpPost || method instanceof HttpPut) { HttpEntityEnclosingRequestBase enclosingRequest = (HttpEntityEnclosingRequestBase) method; if (!formParams.isEmpty()) { // application/x-www-form-urlencoded withContent(RequestUtil.formatQueryString(formParams, UTF_8), MediaType.APPLICATION_FORM_URLENCODED); } if (body != null) { enclosingRequest.setHeader(body.getContentType()); enclosingRequest.setEntity(body); } } if (!headers.isEmpty()) { // headers addHeaders(method, headers); } return method; }
From source file:com.frentix.restapi.RestConnection.java
/** * Attach file to POST request./*w w w . j a v a2s.c o m*/ * * @param post the request * @param filename the filename field * @param file the file * @throws UnsupportedEncodingException */ public void addMultipart(HttpEntityEnclosingRequestBase post, String filename, File file) throws UnsupportedEncodingException { MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE); entity.addPart("filename", new StringBody(filename)); FileBody fileBody = new FileBody(file, "application/octet-stream"); entity.addPart("file", fileBody); post.setEntity(entity); }
From source file:ch.cyberduck.core.googledrive.DriveWriteFeature.java
@Override public HttpResponseOutputStream<Void> write(final Path file, final TransferStatus status, final ConnectionCallback callback) throws BackgroundException { final DelayedHttpEntityCallable<Void> command = new DelayedHttpEntityCallable<Void>() { @Override// w w w .j a va2 s . com public Void call(final AbstractHttpEntity entity) throws BackgroundException { try { final String base = session.getClient().getRootUrl(); // Initiate a resumable upload final HttpEntityEnclosingRequestBase request; if (status.isExists()) { final String fileid = new DriveFileidProvider(session).getFileid(file, new DisabledListProgressListener()); request = new HttpPatch( String.format("%s/upload/drive/v3/files/%s?supportsTeamDrives=true", base, fileid)); if (StringUtils.isNotBlank(status.getMime())) { request.setHeader(HttpHeaders.CONTENT_TYPE, status.getMime()); } // Upload the file request.setEntity(entity); } else { request = new HttpPost(String.format( String.format( "%%s/upload/drive/v3/files?uploadType=resumable&supportsTeamDrives=%s", PreferencesFactory.get().getBoolean("googledrive.teamdrive.enable")), base)); request.setEntity(new StringEntity( "{\"name\": \"" + file.getName() + "\", \"parents\": [\"" + new DriveFileidProvider(session).getFileid(file.getParent(), new DisabledListProgressListener()) + "\"]}", ContentType.create("application/json", "UTF-8"))); if (StringUtils.isNotBlank(status.getMime())) { // Set to the media MIME type of the upload data to be transferred in subsequent requests. request.addHeader("X-Upload-Content-Type", status.getMime()); } } request.addHeader(HTTP.CONTENT_TYPE, MEDIA_TYPE); final HttpClient client = session.getHttpClient(); final HttpResponse response = client.execute(request); try { switch (response.getStatusLine().getStatusCode()) { case HttpStatus.SC_OK: break; default: throw new DriveExceptionMappingService() .map(new HttpResponseException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase())); } } finally { EntityUtils.consume(response.getEntity()); } if (!status.isExists()) { if (response.containsHeader(HttpHeaders.LOCATION)) { final String putTarget = response.getFirstHeader(HttpHeaders.LOCATION).getValue(); // Upload the file final HttpPut put = new HttpPut(putTarget); put.setEntity(entity); final HttpResponse putResponse = client.execute(put); try { switch (putResponse.getStatusLine().getStatusCode()) { case HttpStatus.SC_OK: case HttpStatus.SC_CREATED: break; default: throw new DriveExceptionMappingService().map( new HttpResponseException(putResponse.getStatusLine().getStatusCode(), putResponse.getStatusLine().getReasonPhrase())); } } finally { EntityUtils.consume(putResponse.getEntity()); } } else { throw new DriveExceptionMappingService() .map(new HttpResponseException(response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase())); } } return null; } catch (IOException e) { throw new DriveExceptionMappingService().map("Upload failed", e, file); } } @Override public long getContentLength() { return status.getLength(); } }; return this.write(file, status, command); }