List of usage examples for org.apache.http.client.methods HttpRequestBase addHeader
public void addHeader(String str, String str2)
From source file:org.openo.sdnhub.osdriverservice.openstack.client.http.OpenStackHttpConnection.java
private HttpResult commonRequest(HttpInput input, boolean fromLogin) throws OpenStackException { LOGGER.info("HTTP Request :" + input); if (!fromLogin) { if (this.credentials.getToken() == null) { this.login(); }// w ww . j a va 2 s . co m input.setUri(this.getAbsoluteUrl(input.getContext(), input.getUri())); } this.addCommonHeaders(input); HttpRequestBase requestBase = null; if ("post".equals(input.getMethod())) { HttpPost httpPost = new HttpPost(); httpPost.setEntity(this.getStringEntity(input)); requestBase = httpPost; } else if ("put".equals(input.getMethod())) { HttpPut httpPut = new HttpPut(); httpPut.setEntity(this.getStringEntity(input)); requestBase = httpPut; } else if ("get".equals(input.getMethod())) { requestBase = new HttpGet(); } else if ("delete".equals(input.getMethod())) { requestBase = new HttpDelete(); } else { LOGGER.error("IllegalArgumentException failed. "); throw new IllegalArgumentException("Invalid HTTP method"); } requestBase.setURI(URI.create(input.getUri())); for (Entry<String, String> h : input.getReqHeaders().entrySet()) { requestBase.addHeader(h.getKey(), h.getValue()); } HttpResult result = new HttpResult(); try { HttpResponse resp = this.httpClient.execute(requestBase); String respContent = this.getResponseBody(resp); LOGGER.info("HTTP Request body: " + requestBase); result.setBody(respContent); result.setStatus(resp.getStatusLine().getStatusCode()); result.setRespHeaders(this.getHttpHeaders(resp)); } catch (ParseException | IOException e) { LOGGER.error("HTTP " + requestBase + " failed due to " + e.getMessage()); throw new OpenStackException(e); } finally { HttpGateKeeper.add(input, result); } LOGGER.info("HTTP Response" + result); return result; }
From source file:org.openo.sdnhub.overlayvpndriver.http.OverlayVpnDriverSsoProxy.java
@SuppressWarnings("deprecation") private HTTPReturnMessage commonRequest(HttpRequestBase requestBase) { HTTPReturnMessage msg = new HTTPReturnMessage(); msg.setStatus(FAILED);//from ww w . j av a 2s . co m if (!isParamValide()) { LOGGER.warn("AC Login commonRequest is inValide, Login failed."); return msg; } requestBase.addHeader("Content-Type", APPLICATION_JSON); requestBase.addHeader("Accept", APPLICATION_JSON); try { LOGGER.info(requestBase.toString()); HttpResponse resp = httpClient.execute(requestBase); LOGGER.info(resp.toString()); String respContent = EntityUtils.toString(resp.getEntity(), HTTP.UTF_8); LOGGER.debug("Response status : " + resp.getStatusLine().getStatusCode()); LOGGER.debug("Response body : " + respContent); msg.setBody(respContent); msg.setStatus(resp.getStatusLine().getStatusCode()); this.release(resp); } catch (UnsupportedEncodingException e) { LOGGER.warn("Do Post Request Failed.", e); } catch (ClientProtocolException e) { LOGGER.warn("Do Post Request Failed.", e); } catch (ParseException e) { LOGGER.warn("Do Post Request Failed.", e); } catch (IOException e) { LOGGER.warn("Do Post Request Failed.", e); } catch (IllegalStateException e) { LOGGER.warn("Do Post Request Failed.", e); } return msg; }
From source file:org.openrepose.nodeservice.httpcomponent.HttpComponentRequestProcessor.java
/** * Copy header values from source request to the http method. * * @param method/* w w w.j av a 2 s .c om*/ */ private void setHeaders(HttpRequestBase method) { final Enumeration<String> headerNames = sourceRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { final String headerName = headerNames.nextElement(); if (excludeHeader(headerName)) { continue; } final Enumeration<String> headerValues = sourceRequest.getHeaders(headerName); while (headerValues.hasMoreElements()) { String headerValue = headerValues.nextElement(); method.addHeader(headerName, processHeaderValue(headerName, headerValue)); } } }
From source file:org.openrepose.nodeservice.httpcomponent.RequestProxyServiceImpl.java
private void setHeaders(HttpRequestBase base, Map<String, String> headers) { final Set<Map.Entry<String, String>> entries = headers.entrySet(); for (Map.Entry<String, String> entry : entries) { base.addHeader(entry.getKey(), entry.getValue()); }//from w w w.j a v a 2s . co m //Tack on the tracing ID for requests via the dist datastore String traceGUID = MDC.get(TracingKey.TRACING_KEY); if (!StringUtils.isEmpty(traceGUID)) { Header viaHeader = base.getFirstHeader(CommonHttpHeader.VIA.toString()); base.addHeader(CommonHttpHeader.TRACE_GUID.toString(), TracingHeaderHelper .createTracingHeader(traceGUID, viaHeader != null ? viaHeader.getValue() : null)); } }
From source file:org.rapidoid.http.HttpClient.java
public Future<byte[]> request(String verb, String uri, Map<String, String> headers, Map<String, String> data, Map<String, String> files, byte[] body, String contentType, Callback<byte[]> callback, boolean fullResponse) { headers = U.safe(headers);/* w w w . j ava 2 s .co m*/ data = U.safe(data); files = U.safe(files); HttpRequestBase req; boolean canHaveBody = false; if ("GET".equalsIgnoreCase(verb)) { req = new HttpGet(uri); } else if ("DELETE".equalsIgnoreCase(verb)) { req = new HttpDelete(uri); } else if ("OPTIONS".equalsIgnoreCase(verb)) { req = new HttpOptions(uri); } else if ("HEAD".equalsIgnoreCase(verb)) { req = new HttpHead(uri); } else if ("TRACE".equalsIgnoreCase(verb)) { req = new HttpTrace(uri); } else if ("POST".equalsIgnoreCase(verb)) { req = new HttpPost(uri); canHaveBody = true; } else if ("PUT".equalsIgnoreCase(verb)) { req = new HttpPut(uri); canHaveBody = true; } else if ("PATCH".equalsIgnoreCase(verb)) { req = new HttpPatch(uri); canHaveBody = true; } else { throw U.illegalArg("Illegal HTTP verb: " + verb); } for (Entry<String, String> e : headers.entrySet()) { req.addHeader(e.getKey(), e.getValue()); } if (canHaveBody) { HttpEntityEnclosingRequestBase entityEnclosingReq = (HttpEntityEnclosingRequestBase) req; if (body != null) { NByteArrayEntity entity = new NByteArrayEntity(body); if (contentType != null) { entity.setContentType(contentType); } entityEnclosingReq.setEntity(entity); } else { MultipartEntityBuilder builder = MultipartEntityBuilder.create(); for (Entry<String, String> entry : files.entrySet()) { String filename = entry.getValue(); File file = IO.file(filename); builder = builder.addBinaryBody(entry.getKey(), file, ContentType.DEFAULT_BINARY, filename); } for (Entry<String, String> entry : data.entrySet()) { builder = builder.addTextBody(entry.getKey(), entry.getValue(), ContentType.DEFAULT_TEXT); } ByteArrayOutputStream stream = new ByteArrayOutputStream(); try { builder.build().writeTo(stream); } catch (IOException e) { throw U.rte(e); } byte[] bytes = stream.toByteArray(); NByteArrayEntity entity = new NByteArrayEntity(bytes, ContentType.MULTIPART_FORM_DATA); entityEnclosingReq.setEntity(entity); } } Log.debug("Starting HTTP request", "request", req.getRequestLine()); return execute(client, req, callback, fullResponse); }
From source file:org.structr.rest.common.HttpHelper.java
private static void configure(final HttpRequestBase req, final String username, final String password, final String proxyUrlParameter, final String proxyUsernameParameter, final String proxyPasswordParameter, final String cookieParameter, final Map<String, String> headers, final boolean followRedirects) { if (StringUtils.isBlank(proxyUrlParameter)) { proxyUrl = Settings.HttpProxyUrl.getValue(); } else {/*from w w w . j a v a 2 s . c o m*/ proxyUrl = proxyUrlParameter; } if (StringUtils.isBlank(proxyUsernameParameter)) { proxyUsername = Settings.HttpProxyUser.getValue(); } else { proxyUsername = proxyUsernameParameter; } if (StringUtils.isBlank(proxyPasswordParameter)) { proxyPassword = Settings.HttpProxyPassword.getValue(); } else { proxyPassword = proxyPasswordParameter; } if (!StringUtils.isBlank(cookieParameter)) { cookie = cookieParameter; } //final HttpHost target = HttpHost.create(url.getHost()); HttpHost proxy = null; final CredentialsProvider credsProvider = new BasicCredentialsProvider(); if (StringUtils.isNoneBlank(username, password)) { credsProvider.setCredentials(new AuthScope(new HttpHost(req.getURI().getHost())), new UsernamePasswordCredentials(username, password)); } if (StringUtils.isNotBlank(proxyUrl)) { proxy = HttpHost.create(proxyUrl); if (StringUtils.isNoneBlank(proxyUsername, proxyPassword)) { credsProvider.setCredentials(new AuthScope(proxy), new UsernamePasswordCredentials(proxyUsername, proxyPassword)); } } client = HttpClients.custom().setDefaultConnectionConfig(ConnectionConfig.DEFAULT) .setUserAgent("curl/7.35.0").setDefaultCredentialsProvider(credsProvider).build(); reqConfig = RequestConfig.custom().setProxy(proxy).setRedirectsEnabled(followRedirects) .setCookieSpec(CookieSpecs.DEFAULT).build(); req.setConfig(reqConfig); if (StringUtils.isNotBlank(cookie)) { req.addHeader("Cookie", cookie); req.getParams().setParameter("http.protocol.single-cookie-header", true); } req.addHeader("Connection", "close"); // add request headers from context for (final Map.Entry<String, String> header : headers.entrySet()) { req.addHeader(header.getKey(), header.getValue()); } }
From source file:org.wso2.carbon.apimgt.hybrid.gateway.common.util.HttpRequestUtil.java
/** * Executes the HTTPMethod with retry.// w ww .j av a2 s . c om * * @param httpClient HTTPClient * @param httpMethod HTTPMethod * @param retryCount No of retries * @return response. it will return an empty string if response body is null * @throws OnPremiseGatewayException throws {@link OnPremiseGatewayException} */ public static String executeHTTPMethodWithRetry(HttpClient httpClient, HttpRequestBase httpMethod, int retryCount) throws OnPremiseGatewayException { String result = OnPremiseGatewayConstants.EMPTY_STRING; HttpResponse response; int executionCount = 0; String methodName = httpMethod.getMethod(); String uri = getURI(httpMethod); //Add an unique identifier as a custom header for distinguishing requests from different micro gateways. String token = ConfigManager.getConfigManager() .getProperty(OnPremiseGatewayConstants.API_REQUEST_UNIQUE_IDENTIFIER); if (StringUtils.isNotBlank(token) && !(OnPremiseGatewayConstants.API_REQUEST_UNIQUE_IDENTIFIER_HOLDER.equals(token))) { if (log.isDebugEnabled()) { log.debug("Adding unique identifier as an header to the http " + methodName + " request."); } httpMethod.addHeader(OnPremiseGatewayConstants.APT_REQUEST_TOKEN_HEADER, token); } do { try { executionCount++; response = httpClient.execute(httpMethod); if (log.isDebugEnabled()) { log.debug("HTTP response code for the " + methodName + " request to URL: " + uri + " is " + response); } result = handleResponse(response, methodName, true, executionCount, retryCount, uri); if (!OnPremiseGatewayConstants.EMPTY_STRING.equals(result)) { return result; } } catch (IOException e) { handleExceptionWithRetry(executionCount, retryCount, methodName, uri, e); } finally { httpMethod.releaseConnection(); } } while (executionCount < retryCount); return result; }
From source file:org.wso2.carbon.apimgt.hybrid.gateway.common.util.HttpRequestUtil.java
/** * Executes HTTPMethod without retry//from w w w .j a va 2s .c om * * @param httpClient HTTPClient * @param httpMethod HTTPMethod * @return response. it will return an empty string if response body is null * @throws OnPremiseGatewayException throws {@link OnPremiseGatewayException} */ public static String executeHTTPMethod(HttpClient httpClient, HttpRequestBase httpMethod) throws OnPremiseGatewayException { String result; HttpResponse response; String uri = getURI(httpMethod); String methodName = httpMethod.getMethod(); //Add an unique identifier as an custom header for distinguishing requests from different micro gateways. String token = ConfigManager.getConfigManager() .getProperty(OnPremiseGatewayConstants.API_REQUEST_UNIQUE_IDENTIFIER); if (StringUtils.isNotBlank(token) && !(OnPremiseGatewayConstants.API_REQUEST_UNIQUE_IDENTIFIER_HOLDER.equals(token))) { if (log.isDebugEnabled()) { log.debug("Adding unique identifier as an header to the http " + methodName + " request."); } httpMethod.addHeader(OnPremiseGatewayConstants.APT_REQUEST_TOKEN_HEADER, token); } try { response = httpClient.execute(httpMethod); if (log.isDebugEnabled()) { log.debug("HTTP response code for the " + methodName + " request: " + uri + " is " + response); } result = handleResponse(response, methodName, false, 0, 0, uri); } catch (IOException e) { throw new OnPremiseGatewayException(methodName + " request failed for URI: " + uri, e); } finally { httpMethod.releaseConnection(); } return result; }
From source file:org.wso2.carbon.bpmn.extensions.rest.RESTInvoker.java
private CloseableHttpResponse sendReceiveRequest(HttpRequestBase requestBase, String username, String password) throws IOException { CloseableHttpResponse response;//w ww. j a va 2s . c om if (username != null && !username.equals("") && password != null) { String combinedCredentials = username + ":" + password; byte[] encodedCredentials = Base64.encodeBase64(combinedCredentials.getBytes(StandardCharsets.UTF_8)); requestBase.addHeader("Authorization", "Basic " + new String(encodedCredentials)); response = client.execute(requestBase); } else { response = client.execute(requestBase); } return response; }