Intercept a request and add the oauth headers.

@param req the request
@param body the request body
@param execution the request execution.
@return the request response
@throws IOException on error
184153
@Override
    public ClientHttpResponse intercept(
            HttpRequest req, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        Assert.notNull(propertyResolver);
        Assert.notNull(id);

        try {
            String authString = getOAuthAuthString(req);
            req.getHeaders().add(Headers.Authorization.name(), authString);
        } catch (Exception e) {
            throw new IOException("Error building OAuth header", e);
        }

        return execution.execute(req, body);
    }
1248060
HttpResponse _doHttpRequest(RequestType requestType, String url, String json) throws IOException {
        StringEntity entity = null;

        if (json != null) {
            entity = new StringEntity(json, StandardCharsets.UTF_8.name());
            entity.setContentEncoding(StandardCharsets.UTF_8.name());
            entity.setContentType(ContentType.APPLICATION_JSON.getMimeType());
        }
        switch (requestType) {
            case POST:

                HttpPost post = new HttpPost(url);
                post.setEntity(entity);

                post.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken);
                return _httpClient.execute(post, _httpContext);
            case GET:

                HttpGet httpGet = new HttpGet(url);
                
                httpGet.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken);
                return _httpClient.execute(httpGet, _httpContext);
            case DELETE:

                HttpDelete httpDelete = new HttpDelete(url);
                
                httpDelete.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken);
                return _httpClient.execute(httpDelete, _httpContext);
            case PUT:

                HttpPut httpput = new HttpPut(url);

                httpput.setEntity(entity);
                httpput.setHeader(HttpHeaders.AUTHORIZATION, "Bearer " + accessToken);
                return _httpClient.execute(httpput, _httpContext);
            default:
                throw new IllegalArgumentException(" Request Type " + requestType + " not a valid request type. ");
        }
    }
341076
public T execute() throws ApiException, IOException {
        return client.executeRequest(this.builder, expectedCode, responseClass, needAuth);
    }
245182
protected Response doRequest(HttpRequestBase request, String authorizationToken, Class<?> successResponseClass) {

		assertValid(authorizationToken, "An authorizationToken is required for web resource call");

		CloseableHttpClient httpclient = HttpClients.createDefault();
		request.setHeader(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON);
		request.setHeader(HttpHeaders.ACCEPT, MediaType.APPLICATION_JSON);
		request.setHeader("Authorization", "Token " + authorizationToken);
		
		try {
			CloseableHttpResponse clientResponse = httpclient.execute(request);
		
		    HttpEntity entity = clientResponse.getEntity();

		    InputStream inputStream = entity.getContent();

		    StringWriter writer = new StringWriter();
		    IOUtils.copy(inputStream, writer, "UTF-8");
		    String json = writer.toString();
		    
		    LOG.debug("json: " + json);
		    
			Response response = (Response) OBJECT_MAPPER.readValue(json, successResponseClass);

			LOG.debug("response.statuscode: " + response.status_code);
			
			if (!StatusCode.SUCCESS.equals(response.status_code)) {

				throw new RuntimeException(response.toString());
			}

			Header totalCount = clientResponse.getFirstHeader("X-Total-Count");
			if (totalCount != null) {
				response.totalCount = Integer.valueOf(totalCount.getValue());
			}
		    EntityUtils.consume(entity);
			clientResponse.close();
		    
			LOG.debug("Response: " + response);
		    
			return response;

		} catch (ClientProtocolException e) {
			throw new RuntimeException(e);
		} catch (JsonParseException e) {
			throw new RuntimeException(e);
		} catch (JsonMappingException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
406980
@SuppressWarnings("PMD.AvoidInstantiatingObjectsInLoops")
    private com.jcabi.http.Request request(final Request req,
        final URI dest) throws IOException {
        final String method = new RqMethod.Base(req).method();
        com.jcabi.http.Request proxied = new JdkRequest(dest).method(method);
        final RqHeaders headers = new RqHeaders.Base(req);
        for (final String name : headers.names()) {
            if ("content-length".equals(new EnglishLowerCase(name).string())) {
                continue;
            }
            if (TkProxy.isHost(name)) {
                proxied = proxied.header(name, this.target);
                continue;
            }
            for (final String value : headers.header(name)) {
                proxied = proxied.header(name, value);
            }
        }
        if (headers.header("Content-Length").iterator().hasNext()
            || headers.header("Transfer-Encoding").iterator().hasNext()) {
            final ByteArrayOutputStream output = new ByteArrayOutputStream();
            new RqPrint(new RqLengthAware(req)).printBody(output);
            proxied = proxied.body().set(output.toByteArray()).back();
        }
        return proxied;
    }
313062
protected void doAction(final HttpServletRequest req, final HttpServletResponse resp, String action) {
        // Read the request.
        ApiRequest srequest;
        try {
            srequest = readRequest(req);
            srequest.setType(action);
        } catch (Exception e) {
            writeError(null, resp, e);
            return;
        }

        final CountDownLatch latch = new CountDownLatch(1);
        final ApiRequest finalRequest = srequest;

        // Now execute the request via the apiman engine
        IApiRequestExecutor executor = getEngine().executor(srequest, new IAsyncResultHandler<IEngineResult>() {
            @Override
            public void handle(IAsyncResult<IEngineResult> asyncResult) {
                if (asyncResult.isSuccess()) {
                    IEngineResult engineResult = asyncResult.getResult();
                    if (engineResult.isResponse()) {
                        try {
                            writeResponse(resp, engineResult.getApiResponse());
                            final ServletOutputStream outputStream = resp.getOutputStream();
                            engineResult.bodyHandler(new IAsyncHandler<IApimanBuffer>() {
                                @Override
                                public void handle(IApimanBuffer chunk) {
                                    try {
                                        if (chunk instanceof ByteBuffer) {
                                            byte [] buffer = (byte []) chunk.getNativeBuffer();
                                            outputStream.write(buffer, 0, chunk.length());
                                        } else {
                                            outputStream.write(chunk.getBytes());
                                        }
                                    } catch (IOException e) {
                                        // This will get caught by the API connector, which will abort the
                                        // connection to the back-end API.
                                        throw new RuntimeException(e);
                                    }
                                }
                            });
                            engineResult.endHandler(new IAsyncHandler<Void>() {
                                @Override
                                public void handle(Void result) {
                                    try {
                                        resp.flushBuffer();
                                    } catch (IOException e) {
                                        // This will get caught by the API connector, which will abort the
                                        // connection to the back-end API.
                                        throw new RuntimeException(e);
                                    } finally {
                                        latch.countDown();
                                    }
                                }
                            });
                        } catch (IOException e) {
                            // this would mean we couldn't get the output stream from the response, so we
                            // need to abort the engine result (which will let the back-end connection
                            // close down).
                            engineResult.abort(e);
                            latch.countDown();
                            throw new RuntimeException(e);
                        }
                    } else {
                        writeFailure(finalRequest, resp, engineResult.getPolicyFailure());
                        latch.countDown();
                    }
                } else {
                    writeError(finalRequest, resp, asyncResult.getError());
                    latch.countDown();
                }
            }
        });
        executor.streamHandler(new IAsyncHandler<ISignalWriteStream>() {
            @Override
            public void handle(ISignalWriteStream connectorStream) {
                try {
                    final InputStream is = req.getInputStream();
                    ByteBuffer buffer = new ByteBuffer(2048);
                    int numBytes = buffer.readFrom(is);
                    while (numBytes != -1) {
                        connectorStream.write(buffer);
                        numBytes = buffer.readFrom(is);
                    }
                    connectorStream.end();
                } catch (Throwable e) {
                    connectorStream.abort(e);
                }
            }
        });
        executor.execute();
        try { latch.await(); } catch (InterruptedException e) { }
    }
988874
public String doPost(String url, String body) throws IOException {
        HttpPost httpPost = new HttpPost(getWsapiUrl() + url);
        httpPost.setEntity(new StringEntity(body, "utf-8"));
        return doRequest(httpPost);
    }
315833
static HttpResponse executeHeadRequest(URI uri, SerializationFormat format) throws IOException {

        HttpHead headMethod = new HttpHead(uri);
        MyRedirectHandler redirectHandler = new MyRedirectHandler(uri);

        String acceptHeader = format.getMimeType() != null && ! format.getMimeType().trim().isEmpty() ? format.getMimeType() : "*/*";
        CloseableHttpClient httpClient = HttpClientBuilder
            .create()
            .setDefaultRequestConfig(requestConfig)
            .setConnectionManager(poolingConnManager)
            .setSSLContext(ssl)
            .setRedirectStrategy(redirectHandler)
            .setDefaultHeaders(Arrays.asList(
                new BasicHeader("Accept", acceptHeader), //if default request we try to pretend to be a browser, else we accept everything
                new BasicHeader("User-Agent", "Mozilla/5.0"),
                new BasicHeader("Upgrade-Insecure-Requests", "1")       // we are an all trusting client...
            ))
            .build();

        HttpResponse httpResponse = httpClient.execute(headMethod);
        redirectHandler.lastRedirectedUri.forEach(x -> httpResponse.setHeader(HEADERKEY, String.valueOf(x)));
        return httpResponse;
    }
711314
public static String requestUrl(final String url, final String method, final Properties header, final String body) {
		try {
			final URL siteUrl = new URL(url);
			final HttpURLConnection connection = (HttpURLConnection) siteUrl.openConnection();
			connection.setRequestMethod(method);
			final Enumeration<?> keys = header.keys();
			while (keys.hasMoreElements()) {
				final String key = (String) keys.nextElement();
				connection.addRequestProperty(key, header.getProperty(key));
			}
			connection.setDoOutput(true);

			final OutputStream out = connection.getOutputStream();
			out.write(body.getBytes());

			connection.connect();

			final int errorCode = connection.getResponseCode();
			if (errorCode != HttpURLConnection.HTTP_OK) {
				throw new JKHttpException(connection.getResponseMessage(), errorCode);
			}
			final String response = JKIOUtil.convertToString(connection.getInputStream());
			return response;
		} catch (IOException e) {
			throw new JKHttpException(e);
		}
	}
260360
@Override
    public Response performRequest(Request<?> request,
                                   Map<String, String> additionalHeaders) throws IOException, AuthFailureError {


        String url = request.getUrl();
        HashMap<String, String> map = new HashMap<String, String>();
        map.putAll(request.getHeaders());
        map.putAll(additionalHeaders);
        if (mUrlRewriter != null) {
            String rewritten = mUrlRewriter.rewriteUrl(url);
            if (rewritten == null) {
                throw new IOException("URL blocked by rewriter: " + url);
            }
            url = rewritten;
        }

        com.squareup.okhttp.Request.Builder builder = new com.squareup.okhttp.Request.Builder();
        builder.url(url);

        for (String headerName : map.keySet()) {
            builder.header(headerName, map.get(headerName));
//            connection.addRequestProperty(headerName, map.get(headerName));
            if (VolleyLog.DEBUG) {
                // print header message
                VolleyLog.d("RequestHeader: %1$s:%2$s", headerName, map.get(headerName));
            }
        }
        setConnectionParametersForRequest(builder, request);
        // Initialize HttpResponse with data from the okhttp.
        Response okHttpResponse = mClient.newCall(builder.build()).execute();

        int responseCode = okHttpResponse.code();
        if (responseCode == -1) {
            // -1 is returned by getResponseCode() if the response code could not be retrieved.
            // Signal to the caller that something was wrong with the connection.
            throw new IOException("Could not retrieve response code from HttpUrlConnection.");
        }
        return okHttpResponse;
    }
287758
def _make_request(self, method, url, post_data=None, body=None):
        
        if not self.connection:
            self._connect()
        try:
            self.connection.close()
        except:
            pass
        self.connection.connect()
        headers = {}
        if self.auth_header:
            headers["Authorization"] = self.auth_header
        self.connection.request(method, url, body, headers)
        resp = self.connection.getresponse()
        return resp
784525
private static Request make(final Identity identity, final String header,
        final Request req) throws IOException {
        return new RqWithHeader(
            req,
            header,
            new Utf8String(new CcPlain().encode(identity)).asString()
        );
    }
202551
@Override public Response intercept(Chain chain) throws IOException {
    final Request request = chain.request();
    final Response response = chain.proceed(request);

    if (!response.isSuccessful()) {
      throw new CMAHttpException(request, response);
    }

    return response;
  }
1358668
private void setHeaders(HttpRequest req, HttpURLConnection connection) {
        if (logger.isDebugEnabled()) {
            logger.debug("Request: ");
            logger.debug(req.getMethod().name() + " ", req.getURL());
        }

        String authorizationHeader;
        if (req.getAuthorization() != null && (authorizationHeader = req.getAuthorization().getAuthorizationHeader(req)) != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("Authorization: ", authorizationHeader.replaceAll(".", "*"));
            }
            connection.addRequestProperty("Authorization", authorizationHeader);
        }
        if (req.getRequestHeaders() != null) {
            for (String key : req.getRequestHeaders().keySet()) {
                connection.addRequestProperty(key, req.getRequestHeaders().get(key));
                logger.debug(key + ": " + req.getRequestHeaders().get(key));
            }
        }
    }
1154439
function request(method, address, body, options) {
  let timeout = null;
  return new Promise((resolve, reject) => {
    try {
      const opts = _.merge({}, this.options, options, url.parse(address), {
        method,
      });

      // handle optional timeout
      if (typeof opts.timeout === 'number') {
        setTimeout(() => {
          reject(new Error(`${method} "${address}" timed out`));
          timeout = null;
        }, Math.floor(opts.timeout));
      }

      // create some request middleware to potentially
      // add headers ahead of time for auth or set cors, etc.
      const before =
        typeof opts.before === 'function'
          ? opts.before.call(this.context, method, address, opts)
          : () => null;

      const proto = opts.protocol === 'https:' ? https : http;

      return Promise.resolve(before)
        .then(() => {
          clearTimeout(timeout);

          const req = proto.request(opts, res => {
            let data = '';
            res
              .on('data', d => {
                data += d;
              })
              .on('error', error => {
                clearTimeout(timeout);
                reject(error);
              })
              .on('end', () => {
                clearTimeout(timeout);
                const parsedData = processData(res, data, opts);
                return parsedData instanceof Error
                  ? reject(parsedData)
                  : resolve(parsedData);
              });
          });

          req.on('error', error => {
            clearTimeout(timeout);
            reject(error);
          });

          if (method === Method.PUT || method === Method.POST) {
            req.write(processBody(opts, body));
          }
          req.end();
        })
        .catch(error => {
          clearTimeout(timeout);
          return reject(error);
        });
    } catch (error) {
      clearTimeout(timeout);
      return reject(error);
    }
  });
}
1210001
protected boolean requestRequiresAuthentication(final HttpServletRequest request, final HttpServletResponse response) {
        val accessTokenRequest = isAccessTokenRequest(request, response);
        if (!accessTokenRequest) {
            val extractor = extractAccessTokenGrantRequest(request);
            if (extractor.isPresent()) {
                val ext = extractor.get();
                return ext.requestMustBeAuthenticated();
            }
        } else {
            val extractor = extractAccessTokenGrantRequest(request);
            if (extractor.isPresent()) {
                val ext = extractor.get();
                return ext.getResponseType() != OAuth20ResponseTypes.DEVICE_CODE;
            }
        }
        return false;
    }
687936
private int request (String encoded) throws IOException {
    refreshSignature();
    HttpPost httpPost = new HttpPost(targetURI);
    httpPost.setHeader("Content-type", "application/vnd.microsoft.servicebus.json");
    httpPost.setHeader("Authorization", signature);
    httpPost.setHeader("Host", namespaceName + ".servicebus.windows.net ");

    StringEntity entity = new StringEntity(encoded);
    httpPost.setEntity(entity);

    HttpResponse response = httpclient.execute(httpPost);
    StatusLine status = response.getStatusLine();
    HttpEntity entity2 = response.getEntity();
    // do something useful with the response body
    // and ensure it is fully consumed
    EntityUtils.consume(entity2);

    int returnCode = status.getStatusCode();
    if (returnCode != HttpStatus.SC_CREATED) {
      LOG.error (new IOException(status.getReasonPhrase()).toString());
      throw new IOException(status.getReasonPhrase());
    }

    return returnCode;
  }