List of usage examples for org.apache.http.client.methods HttpEntityEnclosingRequestBase setEntity
public void setEntity(final HttpEntity entity)
From source file:com.android.yijiang.kzx.http.AsyncHttpClient.java
/** * Perform a HTTP POST request and track the Android Context which initiated the request. Set * headers only for this request/*from w w w . jav a 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. * @return RequestHandle of future request process */ public RequestHandle post(Context context, String url, Header[] headers, RequestParams params, String contentType, ResponseHandlerInterface responseHandler) { HttpEntityEnclosingRequestBase request = new HttpPost(URI.create(url).normalize()); 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:org.ballerinalang.composer.service.tryit.service.HttpTryItClient.java
/** * {@inheritDoc}// w w w . jav a 2 s . c om */ @Override public String execute() throws TryItException { try { HttpClient client = HttpClientBuilder.create().build(); HttpCoreContext localContext = new HttpCoreContext(); // Create url for the request. String requestUrl = this.buildUrl(); String httpMethod = this.clientArgs.get(TryItConstants.HTTP_METHOD).getAsString(); switch (httpMethod.toLowerCase(Locale.getDefault())) { case "get": case "delete": case "options": case "head": case "trace": HttpRequestBase httpRequest = new TryItHttpRequestBase(httpMethod.toUpperCase(Locale.getDefault())); // Setting the url for the request. httpRequest.setURI(URI.create(requestUrl)); // Setting the request headers. JsonArray getHeaders = this.clientArgs.getAsJsonArray(TryItConstants.REQUEST_HEADERS); for (JsonElement getHeader : getHeaders) { JsonObject header = getHeader.getAsJsonObject(); if (StringUtils.isNotBlank(header.get("key").getAsString()) && StringUtils.isNotBlank(header.get("value").getAsString())) { httpRequest.setHeader(header.get("key").getAsString(), header.get("value").getAsString()); } } // Setting the content type. if (StringUtils.isBlank(this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString())) { httpRequest.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.TEXT_PLAIN.getMimeType()); } else { httpRequest.setHeader(HttpHeaders.CONTENT_TYPE, this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString()); } // To track how long the request took. long start = System.currentTimeMillis(); // Executing the request. HttpResponse response = client.execute(httpRequest, localContext); long elapsed = System.currentTimeMillis() - start; return jsonStringifyResponse(response, localContext.getRequest().getAllHeaders(), requestUrl, elapsed); default: HttpEntityEnclosingRequestBase httpEntityRequest = new TryItHttpEntityEnclosingRequestBase( httpMethod.toUpperCase(Locale.getDefault())); // Setting the url for the request. httpEntityRequest.setURI(URI.create(requestUrl)); // Setting the request headers. JsonArray getEntityHeaders = this.clientArgs.getAsJsonArray(TryItConstants.REQUEST_HEADERS); for (JsonElement getHeader : getEntityHeaders) { JsonObject header = getHeader.getAsJsonObject(); if (StringUtils.isNotBlank(header.get("key").getAsString()) && StringUtils.isNotBlank(header.get("value").getAsString())) { httpEntityRequest.setHeader(header.get("key").getAsString(), header.get("value").getAsString()); } } // Setting the body of the request. StringEntity postEntity = new StringEntity( this.clientArgs.get(TryItConstants.REQUEST_BODY).getAsString()); httpEntityRequest.setEntity(postEntity); // Setting the content type. if (StringUtils.isBlank(this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString())) { httpEntityRequest.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.TEXT_PLAIN.getMimeType()); } else { httpEntityRequest.setHeader(HttpHeaders.CONTENT_TYPE, this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString()); } // To track how long the request took. long entityRequestStart = System.currentTimeMillis(); // Executing the request. HttpResponse entityResponse = client.execute(httpEntityRequest, localContext); long entityRequestDuration = System.currentTimeMillis() - entityRequestStart; return jsonStringifyResponse(entityResponse, localContext.getRequest().getAllHeaders(), requestUrl, entityRequestDuration); } } catch (IOException e) { throw new TryItException(e.getMessage()); } }
From source file:org.ballerinalang.composer.service.workspace.tryit.HttpTryItClient.java
/** * {@inheritDoc}//from w w w . ja v a 2s . com */ @Override public String execute() throws TryItException { try { HttpClient client = HttpClientBuilder.create().build(); HttpCoreContext localContext = new HttpCoreContext(); // Create url for the request. String requestUrl = this.buildUrl(); String httpMethod = this.clientArgs.get(TryItConstants.HTTP_METHOD).getAsString(); switch (httpMethod.toLowerCase(Locale.getDefault())) { case "get": case "delete": case "options": case "head": case "trace": HttpRequestBase httpRequest = new TryItHttpRequestBase(httpMethod.toUpperCase(Locale.getDefault())); // Setting the url for the request. httpRequest.setURI(URI.create(requestUrl)); // Setting the request headers. JsonArray getHeaders = this.clientArgs.getAsJsonArray(TryItConstants.REQUEST_HEADERS); for (JsonElement getHeader : getHeaders) { JsonObject header = getHeader.getAsJsonObject(); if (StringUtils.isNotBlank(header.get("key").getAsString()) && StringUtils.isNotBlank(header.get("value").getAsString())) { httpRequest.setHeader(header.get("key").getAsString(), header.get("value").getAsString()); } } // Setting the content type. if (StringUtils.isBlank(this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString())) { httpRequest.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.TEXT_PLAIN.getMimeType()); } else { httpRequest.setHeader(HttpHeaders.CONTENT_TYPE, this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString()); } // To track how long the request took. long start = System.currentTimeMillis(); // Executing the request. HttpResponse response = client.execute(httpRequest, localContext); long elapsed = System.currentTimeMillis() - start; return jsonStringifyResponse(response, localContext.getRequest().getAllHeaders(), requestUrl, elapsed); default: HttpEntityEnclosingRequestBase httpEntityRequest = new TryItHttpEntityEnclosingRequestBase( httpMethod.toUpperCase(Locale.getDefault())); // Setting the url for the request. httpEntityRequest.setURI(URI.create(requestUrl)); // Setting the request headers. JsonArray getEntityHeaders = this.clientArgs.getAsJsonArray(TryItConstants.REQUEST_HEADERS); for (JsonElement getHeader : getEntityHeaders) { JsonObject header = getHeader.getAsJsonObject(); if (StringUtils.isNotBlank(header.get("key").getAsString()) && StringUtils.isNotBlank(header.get("value").getAsString())) { httpEntityRequest.setHeader(header.get("key").getAsString(), header.get("value").getAsString()); } } // Setting the body of the request. StringEntity postEntity = new StringEntity( this.clientArgs.get(TryItConstants.REQUEST_BODY).getAsString()); httpEntityRequest.setEntity(postEntity); // Setting the content type. if (StringUtils.isBlank(this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString())) { httpEntityRequest.setHeader(HttpHeaders.CONTENT_TYPE, ContentType.TEXT_PLAIN.getMimeType()); } else { httpEntityRequest.setHeader(HttpHeaders.CONTENT_TYPE, this.clientArgs.get(TryItConstants.CONTENT_TYPE).getAsString()); } // To track how long the request took. long entityRequestStart = System.currentTimeMillis(); // Executing the request. HttpResponse entityResponse = client.execute(httpEntityRequest, localContext); long entityRequestDuration = System.currentTimeMillis() - entityRequestStart; return jsonStringifyResponse(entityResponse, localContext.getRequest().getAllHeaders(), requestUrl, entityRequestDuration); } } catch (java.io.IOException e) { throw new TryItException(e.getMessage()); } }
From source file:com.streamreduce.util.WebHDFSClient.java
private void writeToFile(String target, String operation, byte[] contents) throws IOException { String targetUrl = target == null ? String.format("%s?op=%s&user.name=%s", url, operation, username) : String.format("%s/%s?op=%s&user.name=%s", trimUrl(url), target, operation, username); HttpEntityEnclosingRequestBase method = getWriteMethod(operation, targetUrl); int responseCode; HttpResponse response = null;//from ww w.j av a2 s . c o m try { response = httpClient.execute(method); StatusLine status = response.getStatusLine(); responseCode = response.getStatusLine().getStatusCode(); if (responseCode != 307) { throw new IOException(String.format("Error returned from server. Status: %s - %s", responseCode, status.getReasonPhrase())); } } catch (IOException e) { method.abort(); throw e; } finally { method.releaseConnection(); } try { Header redirectUrl = response.getFirstHeader("Location"); if (redirectUrl == null) { throw new IOException(String.format( "Location header, indicating data node location, is null. Cannot continue appending to %s.", url)); } method = getWriteMethod(operation, redirectUrl.getValue()); method.setEntity(new ByteArrayEntity(contents)); response = httpClient.execute(method); StatusLine status = response.getStatusLine(); responseCode = response.getStatusLine().getStatusCode(); HttpEntity entity = response.getEntity(); if (entity != null) { EntityUtils.consume(entity); } if (responseCode != 200 && responseCode != 201) { throw new IOException(String.format("Error returned from server. Status: %s - %s; %s", responseCode, status.getReasonPhrase(), readResponse(entity))); } } catch (IOException e) { method.abort(); throw e; } finally { method.releaseConnection(); } }
From source file:org.apache.solr.servlet.HttpSolrCall.java
private void remoteQuery(String coreUrl, HttpServletResponse resp) throws IOException { HttpRequestBase method = null;//from ww w .j av a 2 s . co m HttpEntity httpEntity = null; try { String urlstr = coreUrl + queryParams.toQueryString(); boolean isPostOrPutRequest = "POST".equals(req.getMethod()) || "PUT".equals(req.getMethod()); if ("GET".equals(req.getMethod())) { method = new HttpGet(urlstr); } else if ("HEAD".equals(req.getMethod())) { method = new HttpHead(urlstr); } else if (isPostOrPutRequest) { HttpEntityEnclosingRequestBase entityRequest = "POST".equals(req.getMethod()) ? new HttpPost(urlstr) : new HttpPut(urlstr); InputStream in = new CloseShieldInputStream(req.getInputStream()); // Prevent close of container streams HttpEntity entity = new InputStreamEntity(in, req.getContentLength()); entityRequest.setEntity(entity); method = entityRequest; } else if ("DELETE".equals(req.getMethod())) { method = new HttpDelete(urlstr); } else { throw new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Unexpected method type: " + req.getMethod()); } for (Enumeration<String> e = req.getHeaderNames(); e.hasMoreElements();) { String headerName = e.nextElement(); if (!"host".equalsIgnoreCase(headerName) && !"authorization".equalsIgnoreCase(headerName) && !"accept".equalsIgnoreCase(headerName)) { method.addHeader(headerName, req.getHeader(headerName)); } } // These headers not supported for HttpEntityEnclosingRequests if (method instanceof HttpEntityEnclosingRequest) { method.removeHeaders(TRANSFER_ENCODING_HEADER); method.removeHeaders(CONTENT_LENGTH_HEADER); } final HttpResponse response = solrDispatchFilter.httpClient.execute(method, HttpClientUtil.createNewHttpClientRequestContext()); int httpStatus = response.getStatusLine().getStatusCode(); httpEntity = response.getEntity(); resp.setStatus(httpStatus); for (HeaderIterator responseHeaders = response.headerIterator(); responseHeaders.hasNext();) { Header header = responseHeaders.nextHeader(); // We pull out these two headers below because they can cause chunked // encoding issues with Tomcat if (header != null && !header.getName().equalsIgnoreCase(TRANSFER_ENCODING_HEADER) && !header.getName().equalsIgnoreCase(CONNECTION_HEADER)) { resp.addHeader(header.getName(), header.getValue()); } } if (httpEntity != null) { if (httpEntity.getContentEncoding() != null) resp.setCharacterEncoding(httpEntity.getContentEncoding().getValue()); if (httpEntity.getContentType() != null) resp.setContentType(httpEntity.getContentType().getValue()); InputStream is = httpEntity.getContent(); OutputStream os = resp.getOutputStream(); IOUtils.copyLarge(is, os); } } catch (IOException e) { sendError(new SolrException(SolrException.ErrorCode.SERVER_ERROR, "Error trying to proxy request for url: " + coreUrl, e)); } finally { Utils.consumeFully(httpEntity); } }
From source file:com.soundcloud.playerapi.Request.java
/** * Builds a request with the given set of parameters and files. * @param method the type of request to use * @param <T> the type of request to use * @return HTTP request, prepared to be executed */// w w w .j a v a 2 s . c o m public <T extends HttpRequestBase> T buildRequest(Class<T> method) { try { T request = method.newInstance(); // POST/PUT ? if (request instanceof HttpEntityEnclosingRequestBase) { HttpEntityEnclosingRequestBase enclosingRequest = (HttpEntityEnclosingRequestBase) request; final Charset charSet = java.nio.charset.Charset.forName(UTF_8); if (isMultipart()) { MultipartEntity multiPart = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, // XXX change this to STRICT once rack on server is upgraded null, charSet); if (mFiles != null) { for (Map.Entry<String, Attachment> e : mFiles.entrySet()) { multiPart.addPart(e.getKey(), e.getValue().toContentBody()); } } for (NameValuePair pair : mParams) { multiPart.addPart(pair.getName(), new StringBody(pair.getValue(), "text/plain", charSet)); } enclosingRequest.setEntity( listener == null ? multiPart : new CountingMultipartEntity(multiPart, listener)); request.setURI(URI.create(mResource)); // form-urlencoded? } else if (mEntity != null) { request.setHeader(mEntity.getContentType()); enclosingRequest.setEntity(mEntity); request.setURI(URI.create(toUrl())); // include the params } else { if (!mParams.isEmpty()) { request.setHeader("Content-Type", "application/x-www-form-urlencoded"); enclosingRequest.setEntity(new StringEntity(queryString())); } request.setURI(URI.create(mResource)); } } else { // just plain GET/HEAD/DELETE/... if (mRange != null) { request.addHeader("Range", formatRange(mRange)); } if (mIfNoneMatch != null) { request.addHeader("If-None-Match", mIfNoneMatch); } request.setURI(URI.create(toUrl())); } if (mToken != null) { request.addHeader(ApiWrapper.createOAuthHeader(mToken)); } return request; } catch (InstantiationException e) { throw new RuntimeException(e); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e); } }
From source file:com.corebase.android.framework.http.client.AsyncHttpClient.java
public void post(String url, Map<String, String> clientHeaderMap, RequestParams params, String contentType, AsyncHttpResponseHandler responseHandler) { HttpEntityEnclosingRequestBase request; if (null == url || "".equals(url)) return;/*from w w w .ja va 2 s.c o m*/ try { request = new HttpPost(url); } catch (IllegalArgumentException e) { responseHandler.sendFailureMessage(null, e, "uri is invalid"); e.printStackTrace(); return; } if (params != null) request.setEntity(paramsToEntity(params)); if (clientHeaderMap != null && clientHeaderMap.size() > 0) { for (String header : clientHeaderMap.keySet()) { request.addHeader(header, clientHeaderMap.get(header)); } } setTimeout(socketTimeout); // if(headers != null) request.setHeaders(headers); sendRequest(httpClient, httpContext, request, contentType, null, responseHandler, null); }
From source file:eu.fusepool.p3.webid.proxy.ProxyServlet.java
/** * The service method from HttpServlet, performs handling of all * HTTP-requests independent of their method. Requests and responses within * the method can be distinguished by belonging to the "frontend" (i.e. the * client connecting to the proxy) or the "backend" (the server being * contacted on behalf of the client)//from w w w. ja va2 s . co m * * @param frontendRequest Request coming in from the client * @param frontendResponse Response being returned to the client * @throws ServletException * @throws IOException */ @Override protected void service(final HttpServletRequest frontendRequest, final HttpServletResponse frontendResponse) throws ServletException, IOException { log(LogService.LOG_INFO, "Proxying request: " + frontendRequest.getRemoteAddr() + ":" + frontendRequest.getRemotePort() + " (" + frontendRequest.getHeader("Host") + ") " + frontendRequest.getMethod() + " " + frontendRequest.getRequestURI()); if (targetBaseUri == null) { // FIXME return status page return; } //////////////////// Setup backend request final HttpEntityEnclosingRequestBase backendRequest = new HttpEntityEnclosingRequestBase() { @Override public String getMethod() { return frontendRequest.getMethod(); } }; try { backendRequest.setURI(new URL(targetBaseUri + frontendRequest.getRequestURI()).toURI()); } catch (URISyntaxException ex) { throw new IOException(ex); } //////////////////// Copy headers to backend request final Enumeration<String> frontendHeaderNames = frontendRequest.getHeaderNames(); while (frontendHeaderNames.hasMoreElements()) { final String headerName = frontendHeaderNames.nextElement(); final Enumeration<String> headerValues = frontendRequest.getHeaders(headerName); while (headerValues.hasMoreElements()) { final String headerValue = headerValues.nextElement(); if (!headerName.equalsIgnoreCase("Content-Length")) { backendRequest.setHeader(headerName, headerValue); } } } //////////////////// Copy Entity - if any final byte[] inEntityBytes = IOUtils.toByteArray(frontendRequest.getInputStream()); if (inEntityBytes.length > 0) { backendRequest.setEntity(new ByteArrayEntity(inEntityBytes)); } //////////////////// Execute request to backend try (CloseableHttpResponse backendResponse = httpclient.execute(backendRequest)) { frontendResponse.setStatus(backendResponse.getStatusLine().getStatusCode()); // Copy back headers final Header[] backendHeaders = backendResponse.getAllHeaders(); final Set<String> backendHeaderNames = new HashSet<>(backendHeaders.length); for (Header header : backendHeaders) { if (backendHeaderNames.add(header.getName())) { frontendResponse.setHeader(header.getName(), header.getValue()); } else { frontendResponse.addHeader(header.getName(), header.getValue()); } } final ServletOutputStream outStream = frontendResponse.getOutputStream(); // Copy back entity final HttpEntity entity = backendResponse.getEntity(); if (entity != null) { try (InputStream inStream = entity.getContent()) { IOUtils.copy(inStream, outStream); } } outStream.flush(); } }
From source file:com.corebase.android.framework.http.client.AsyncHttpClient.java
/** * Perform a HTTP POST request and track the Android Context which initiated * the request. Set headers only for this request * /*from w ww .j a v a2 s . 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, String url, Map<String, String> clientHeaderMap, RequestParams params, String contentType, AsyncHttpResponseHandler responseHandler) { HttpEntityEnclosingRequestBase request; if (null == url || "".equals(url)) return; try { request = new HttpPost(url); } catch (IllegalArgumentException e) { responseHandler.sendFailureMessage(context, e, "uri is invalid"); e.printStackTrace(); return; } if (params != null) request.setEntity(paramsToEntity(params)); if (clientHeaderMap != null && clientHeaderMap.size() > 0) { for (String header : clientHeaderMap.keySet()) { request.addHeader(header, clientHeaderMap.get(header)); } } setTimeout(socketTimeout); sendRequest(httpClient, httpContext, request, contentType, null, responseHandler, context); }