List of usage examples for org.apache.http.client.methods HttpEntityEnclosingRequestBase setEntity
public void setEntity(final HttpEntity entity)
From source file:com.flyn.net.asynchttp.AsyncHttpClient.java
/** * Perform a HTTP POST request and track the Android Context which initiated * the request. Set headers only for this request * * @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. * @return RequestHandle of future request process *//* w w w. j a v a2 s.co m*/ public RequestHandle post(Context context, String url, Header[] headers, RequestParams params, String contentType, ResponseHandlerInterface responseHandler) { HttpEntityEnclosingRequestBase request = new HttpPost(url); if (params != null) { request.setEntity(paramsToEntity(params, responseHandler)); } if (headers != null) { request.setHeaders(headers); } return sendRequest(httpClient, httpContext, request, contentType, responseHandler, context); }
From source file:com.google.code.jerseyclients.httpclientfour.ApacheHttpClientFourHandler.java
public ClientResponse handle(final ClientRequest clientRequest) throws ClientHandlerException { if (this.jerseyHttpClientConfig.getApplicationCode() != null) { clientRequest.getHeaders().add(this.jerseyHttpClientConfig.getApplicationCodeHeader(), this.jerseyHttpClientConfig.getApplicationCode()); }// w w w . ja va 2 s .c o m if (this.jerseyHttpClientConfig.getOptionnalHeaders() != null) { for (Entry<String, String> entry : this.jerseyHttpClientConfig.getOptionnalHeaders().entrySet()) { clientRequest.getHeaders().add(entry.getKey(), entry.getValue()); } } // final Map<String, Object> props = cr.getProperties(); final HttpRequestBase method = getHttpMethod(clientRequest); // Set the read timeout final Integer readTimeout = jerseyHttpClientConfig.getReadTimeOut(); if (readTimeout != null) { HttpConnectionParams.setSoTimeout(method.getParams(), readTimeout.intValue()); } // FIXME penser au header http // DEBUG|wire.header|>> "Cache-Control: no-cache[\r][\n]" // DEBUG|wire.header|>> "Pragma: no-cache[\r][\n]" if (method instanceof HttpEntityEnclosingRequestBase) { final HttpEntityEnclosingRequestBase entMethod = (HttpEntityEnclosingRequestBase) method; if (clientRequest.getEntity() != null) { final RequestEntityWriter re = getRequestEntityWriter(clientRequest); ByteArrayOutputStream baos = new ByteArrayOutputStream(); try { re.writeRequestEntity(new CommittingOutputStream(baos) { @Override protected void commit() throws IOException { writeOutBoundHeaders(clientRequest.getHeaders(), method); } }); } catch (IOException ex) { throw new ClientHandlerException(ex); } final byte[] content = baos.toByteArray(); HttpEntity httpEntity = new ByteArrayEntity(content); entMethod.setEntity(httpEntity); } } else { writeOutBoundHeaders(clientRequest.getHeaders(), method); } try { StopWatch stopWatch = new StopWatch(); stopWatch.reset(); stopWatch.start(); HttpResponse httpResponse = client.execute(method); int httpReturnCode = httpResponse.getStatusLine().getStatusCode(); stopWatch.stop(); log.info("time to call rest url " + clientRequest.getURI() + ", " + stopWatch.getTime() + " ms"); if (httpReturnCode == Status.NO_CONTENT.getStatusCode()) { return new ClientResponse(httpReturnCode, getInBoundHeaders(httpResponse), IOUtils.toInputStream(""), getMessageBodyWorkers()); } return new ClientResponse(httpReturnCode, getInBoundHeaders(httpResponse), httpResponse.getEntity() == null ? IOUtils.toInputStream("") : httpResponse.getEntity().getContent(), getMessageBodyWorkers()); } catch (Exception e) { throw new ClientHandlerException(e); } }
From source file:com.wen.security.http.AsyncHttpClient.java
/** * Applicable only to HttpRequest methods extending HttpEntityEnclosingRequestBase, which is for * example not DELETE/*from w w w . j a va 2 s. c o m*/ * * @param entity entity to be included within the request * @param requestBase HttpRequest instance, must not be null */ private HttpEntityEnclosingRequestBase addEntityToRequestBase(HttpEntityEnclosingRequestBase requestBase, HttpEntity entity) { if (entity != null) { requestBase.setEntity(entity); } return requestBase; }
From source file:org.attribyte.api.http.impl.commons.Commons4Client.java
@Override public Response send(Request request, RequestOptions options) throws IOException { HttpUriRequest commonsRequest = null; switch (request.getMethod()) { case GET:/*from w w w . j av a2 s.c o m*/ commonsRequest = new HttpGet(request.getURI()); break; case DELETE: commonsRequest = new HttpDelete(request.getURI()); break; case HEAD: commonsRequest = new HttpHead(request.getURI()); break; case POST: { HttpEntityEnclosingRequestBase entityEnclosingRequest = new HttpPost(request.getURI()); commonsRequest = entityEnclosingRequest; EntityBuilder entityBuilder = EntityBuilder.create(); if (request.getBody() != null) { entityBuilder.setBinary(request.getBody().toByteArray()); } else { Collection<Parameter> parameters = request.getParameters(); List<NameValuePair> nameValuePairs = Lists.newArrayListWithExpectedSize(parameters.size()); for (Parameter parameter : parameters) { String[] values = parameter.getValues(); for (String value : values) { nameValuePairs.add(new BasicNameValuePair(parameter.getName(), value)); } } } entityEnclosingRequest.setEntity(entityBuilder.build()); break; } case PUT: { HttpEntityEnclosingRequestBase entityEnclosingRequest = new HttpPut(request.getURI()); commonsRequest = entityEnclosingRequest; EntityBuilder entityBuilder = EntityBuilder.create(); if (request.getBody() != null) { entityBuilder.setBinary(request.getBody().toByteArray()); } entityEnclosingRequest.setEntity(entityBuilder.build()); break; } } Collection<Header> headers = request.getHeaders(); for (Header header : headers) { String[] values = header.getValues(); for (String value : values) { commonsRequest.setHeader(header.getName(), value); } } ResponseBuilder builder = new ResponseBuilder(); CloseableHttpResponse response = null; InputStream is = null; try { if (options.followRedirects != RequestOptions.DEFAULT_FOLLOW_REDIRECTS) { RequestConfig localConfig = RequestConfig.copy(defaultRequestConfig) .setRedirectsEnabled(options.followRedirects) .setMaxRedirects(options.followRedirects ? 5 : 0).build(); HttpClientContext localContext = HttpClientContext.create(); localContext.setRequestConfig(localConfig); response = httpClient.execute(commonsRequest, localContext); } else { response = httpClient.execute(commonsRequest); } builder.setStatusCode(response.getStatusLine().getStatusCode()); for (org.apache.http.Header header : response.getAllHeaders()) { builder.addHeader(header.getName(), header.getValue()); } HttpEntity entity = response.getEntity(); if (entity != null) { is = entity.getContent(); if (is != null) { builder.setBody(Request.bodyFromInputStream(is, options.maxResponseBytes)); } } } finally { if (is != null) { try { is.close(); } catch (IOException ioe) { //TODO? } } if (response != null) { response.close(); } } return builder.create(); }
From source file:org.bedework.util.http.BasicHttpClient.java
/** Send content * * @param content the content as bytes// w w w.ja va 2 s . c om * @param contentType its type * @throws HttpException */ public void setContent(final byte[] content, final String contentType) throws HttpException { if (!(method instanceof HttpEntityEnclosingRequestBase)) { throw new HttpException("Invalid operation for method " + method.getMethod()); } final HttpEntityEnclosingRequestBase eem = (HttpEntityEnclosingRequestBase) method; ByteArrayEntity entity = new ByteArrayEntity(content); entity.setContentType(contentType); eem.setEntity(entity); }
From source file:nl.architolk.ldt.processors.HttpClientProcessor.java
private void setBody(HttpEntityEnclosingRequestBase httpRequest, PipelineContext context, Node configNode) throws IOException { Document dataDocument = readInputAsDOM4J(context, INPUT_DATA); if (configNode.valueOf("input-type").equals("form")) { List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(); Element rootElement = dataDocument.getRootElement(); Iterator<?> elit = rootElement.elementIterator(); while (elit.hasNext()) { Element child = (Element) elit.next(); nameValuePairs.add(new BasicNameValuePair(child.getQName().getName(), child.getText())); }//from w w w . jav a 2 s . c o m httpRequest.setEntity(new UrlEncodedFormEntity(nameValuePairs)); } else { String jsonstr; if (configNode.valueOf("input-type").equals("json")) { //Conversion of XML input to JSON JSONObject jsondata = new JSONObject(); populateJSONObject(jsondata, dataDocument); jsonstr = jsondata.toString(); } else { //No conversion, just use plain text in input jsonstr = dataDocument.getRootElement().getText(); } httpRequest.setEntity(new StringEntity(jsonstr)); } }
From source file:org.fcrepo.test.api.TestAdminAPI.java
private HttpResponse putOrPost(String method, Object requestContent, boolean authenticate) throws Exception { if (url == null || url.length() == 0) { throw new IllegalArgumentException("url must be a non-empty value"); } else if (!(url.startsWith("http://") || url.startsWith("https://"))) { url = getBaseURL() + url;//from w w w .j av a2 s . c om } HttpEntityEnclosingRequestBase httpMethod = null; try { if (method.equals("PUT")) { httpMethod = new HttpPut(url); } else if (method.equals("POST")) { httpMethod = new HttpPost(url); } else { throw new IllegalArgumentException("method must be one of PUT or POST."); } httpMethod.setHeader(HttpHeaders.CONNECTION, "Keep-Alive"); if (requestContent != null) { if (requestContent instanceof String) { StringEntity entity = new StringEntity((String) requestContent, Charset.forName("UTF-8")); entity.setChunked(chunked); httpMethod.setEntity(entity); } else if (requestContent instanceof File) { MultipartEntity entity = new MultipartEntity(); entity.addPart(((File) requestContent).getName(), new FileBody((File) requestContent)); entity.addPart("param_name", new StringBody("value")); httpMethod.setEntity(entity); } else { throw new IllegalArgumentException("requestContent must be a String or File"); } } return getClient(authenticate).execute(httpMethod); } finally { if (httpMethod != null) { httpMethod.releaseConnection(); } } }
From source file:com.mikecorrigan.bohrium.pubsub.Transaction.java
private int readWrite(HttpEntityEnclosingRequestBase request) { Log.v(TAG, "readWrite"); CookieStore mCookieStore = new BasicCookieStore(); mCookieStore.addCookie(mAuthCookie); DefaultHttpClient httpClient = new DefaultHttpClient(); BasicHttpContext mHttpContext = new BasicHttpContext(); mHttpContext.setAttribute(ClientContext.COOKIE_STORE, mCookieStore); // Encode request body. StringEntity requestEntity;/*from w w w. jav a 2s. c o m*/ try { requestEntity = new StringEntity(encode(mRequestBody)); } catch (UnsupportedEncodingException e) { Log.e(TAG, "HTTP encoding failed=" + e); return mStatusCode; } try { final HttpParams getParams = new BasicHttpParams(); HttpClientParams.setRedirecting(getParams, false); request.setParams(getParams); request.setHeader("Content-Type", getMimeType()); request.setEntity(requestEntity); HttpResponse response = httpClient.execute(request, mHttpContext); Log.d(TAG, "status=" + response.getStatusLine()); // Read response body. HttpEntity responseEntity = response.getEntity(); if (responseEntity != null) { InputStream is = responseEntity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8); StringBuilder sb = new StringBuilder(); String line; while ((line = reader.readLine()) != null) { sb.append(line); sb.append("\n"); } is.close(); mStatusCode = response.getStatusLine().getStatusCode(); mStatusReason = response.getStatusLine().getReasonPhrase(); if (mStatusCode == 200) { mResponseBody = decode(sb.toString()); Log.v(TAG, "mResponseBody=" + sb.toString()); } return mStatusCode; } } catch (IOException e) { Log.e(TAG, "exception=" + e); Log.e(TAG, Log.getStackTraceString(e)); } finally { httpClient.getParams().setBooleanParameter(ClientPNames.HANDLE_REDIRECTS, true); } return mStatusCode; }
From source file:com.adobe.ags.curly.controller.ActionRunner.java
private void addPostParams(HttpEntityEnclosingRequestBase request) throws UnsupportedEncodingException { final MultipartEntityBuilder multipartBuilder = MultipartEntityBuilder.create(); List<NameValuePair> formParams = new ArrayList<>(); postVariables.forEach((name, values) -> values.forEach(value -> { if (multipart) { if (value.startsWith("@")) { File f = new File(value.substring(1)); multipartBuilder.addBinaryBody(name, f, ContentType.DEFAULT_BINARY, f.getName()); } else { multipartBuilder.addTextBody(name, value); }/*from w ww. j a v a2 s. c o m*/ } else { formParams.add(new BasicNameValuePair(name, value)); } })); if (multipart) { request.setEntity(multipartBuilder.build()); } else { request.setEntity(new UrlEncodedFormEntity(formParams)); } }
From source file:org.dasein.cloud.azure.AzureMethod.java
public void tempRedirectInvoke(@Nonnull String tempEndpoint, @Nonnull String method, @Nonnull String account, @Nonnull String resource, @Nonnull String body) throws CloudException, InternalException { if (logger.isTraceEnabled()) { logger.trace("enter - " + AzureMethod.class.getName() + ".post(" + account + "," + resource + ")"); }/*from w w w . j av a 2 s .c om*/ if (wire.isDebugEnabled()) { wire.debug("POST --------------------------------------------------------> " + endpoint + account + resource); wire.debug(""); } try { HttpClient client = getClient(); String url = tempEndpoint + account + resource; HttpRequestBase httpMethod = getMethod(method, url); //If it is networking configuration services if (httpMethod instanceof HttpPut) { if (url.endsWith("/services/networking/media")) { httpMethod.addHeader("Content-Type", "text/plain"); } else { httpMethod.addHeader("Content-Type", "application/xml;charset=UTF-8"); } } else { httpMethod.addHeader("Content-Type", "application/xml;charset=UTF-8"); } //dmayne version is older for anything to do with images and for disk deletion if (url.indexOf("/services/images") > -1 || (httpMethod instanceof HttpDelete && url.indexOf("/services/disks") > -1)) { httpMethod.addHeader("x-ms-version", "2012-08-01"); } else { httpMethod.addHeader("x-ms-version", "2012-03-01"); } if (wire.isDebugEnabled()) { wire.debug(httpMethod.getRequestLine().toString()); for (Header header : httpMethod.getAllHeaders()) { wire.debug(header.getName() + ": " + header.getValue()); } wire.debug(""); if (body != null) { wire.debug(body); wire.debug(""); } } if (httpMethod instanceof HttpEntityEnclosingRequestBase) { HttpEntityEnclosingRequestBase entityEnclosingMethod = (HttpEntityEnclosingRequestBase) httpMethod; if (body != null) { try { entityEnclosingMethod.setEntity(new StringEntity(body, "application/xml", "utf-8")); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } HttpResponse response; StatusLine status; try { response = client.execute(httpMethod); status = response.getStatusLine(); } catch (IOException e) { logger.error("post(): Failed to execute HTTP request due to a cloud I/O error: " + e.getMessage()); if (logger.isTraceEnabled()) { e.printStackTrace(); } throw new CloudException(e); } if (logger.isDebugEnabled()) { logger.debug("post(): HTTP Status " + status); } Header[] headers = response.getAllHeaders(); if (wire.isDebugEnabled()) { wire.debug(status.toString()); for (Header h : headers) { if (h.getValue() != null) { wire.debug(h.getName() + ": " + h.getValue().trim()); } else { wire.debug(h.getName() + ":"); } } wire.debug(""); } if (status.getStatusCode() != HttpServletResponse.SC_OK && status.getStatusCode() != HttpServletResponse.SC_CREATED && status.getStatusCode() != HttpServletResponse.SC_ACCEPTED) { logger.error("post(): Expected OK for GET request, got " + status.getStatusCode()); HttpEntity entity = response.getEntity(); if (entity == null) { throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), "An error was returned without explanation"); } try { body = EntityUtils.toString(entity); } catch (IOException e) { throw new AzureException(CloudErrorType.GENERAL, status.getStatusCode(), status.getReasonPhrase(), e.getMessage()); } if (wire.isDebugEnabled()) { wire.debug(body); } wire.debug(""); AzureException.ExceptionItems items = AzureException.parseException(status.getStatusCode(), body); if (items == null) { throw new CloudException(CloudErrorType.GENERAL, status.getStatusCode(), "Unknown", "Unknown"); } logger.error("post(): [" + status.getStatusCode() + " : " + items.message + "] " + items.details); throw new AzureException(items); } } finally { if (logger.isTraceEnabled()) { logger.trace("exit - " + AzureMethod.class.getName() + ".post()"); } if (wire.isDebugEnabled()) { wire.debug(""); wire.debug("POST --------------------------------------------------------> " + endpoint + account + resource); } } }