List of usage examples for org.apache.http.client.methods HttpUriRequest setHeader
void setHeader(String str, String str2);
From source file:com.tremolosecurity.unison.proxy.auth.twitter.TwitterAuth.java
private void signRequest(HttpUriRequest request, String postParams, String token, String tokenSecret, String consumerKey, String consumerSecret) { // TODO: this is a little odd: we already encoded the values earlier, but using URLEncodedUtils.parse will decode the values, // which we will encode again. List<NameValuePair> httpGetParams = null; if (request.getURI().getRawQuery() == null) { httpGetParams = new ArrayList<NameValuePair>(); } else {//from w w w .j a va 2 s. co m httpGetParams = URLEncodedUtils.parse(request.getURI().getRawQuery(), Charsets.UTF_8); } List<Pair> javaParams = new ArrayList<Pair>(httpGetParams.size()); for (NameValuePair params : httpGetParams) { Pair tuple = new Pair(UrlCodec.encode(params.getName()), UrlCodec.encode(params.getValue())); javaParams.add(tuple); } if (postParams != null) { List<NameValuePair> httpPostParams = URLEncodedUtils.parse(postParams, Charsets.UTF_8); for (NameValuePair params : httpPostParams) { Pair tuple = new Pair(UrlCodec.encode(params.getName()), UrlCodec.encode(params.getValue())); javaParams.add(tuple); } } long timestampSecs = generateTimestamp(); String nonce = generateNonce(); OAuthParams.OAuth1Params oAuth1Params = new OAuthParams.OAuth1Params(token, consumerKey, nonce, timestampSecs, Long.toString(timestampSecs), "", OAuthParams.HMAC_SHA1, OAuthParams.ONE_DOT_OH); int port = request.getURI().getPort(); if (port <= 0) { // getURI can return a -1 for a port if (request.getURI().getScheme().equalsIgnoreCase(HttpConstants.HTTP_SCHEME)) { port = HttpConstants.DEFAULT_HTTP_PORT; } else if (request.getURI().getScheme().equalsIgnoreCase(HttpConstants.HTTPS_SCHEME)) { port = HttpConstants.DEFAULT_HTTPS_PORT; } else { throw new IllegalStateException("Bad URI scheme: " + request.getURI().getScheme()); } } String normalized = Normalizer.getStandardNormalizer().normalize(request.getURI().getScheme(), request.getURI().getHost(), port, request.getMethod().toUpperCase(), request.getURI().getPath(), javaParams, oAuth1Params); String signature; try { signature = Signer.getStandardSigner().getString(normalized, tokenSecret, consumerSecret); } catch (InvalidKeyException e) { throw new RuntimeException(e); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } Map<String, String> oauthHeaders = new HashMap<String, String>(); oauthHeaders.put(OAuthParams.OAUTH_CONSUMER_KEY, quoted(consumerKey)); oauthHeaders.put(OAuthParams.OAUTH_TOKEN, quoted(token)); oauthHeaders.put(OAuthParams.OAUTH_SIGNATURE, quoted(signature)); oauthHeaders.put(OAuthParams.OAUTH_SIGNATURE_METHOD, quoted(OAuthParams.HMAC_SHA1)); oauthHeaders.put(OAuthParams.OAUTH_TIMESTAMP, quoted(Long.toString(timestampSecs))); oauthHeaders.put(OAuthParams.OAUTH_NONCE, quoted(nonce)); oauthHeaders.put(OAuthParams.OAUTH_VERSION, quoted(OAuthParams.ONE_DOT_OH)); String header = Joiner.on(", ").withKeyValueSeparator("=").join(oauthHeaders); request.setHeader(HttpHeaders.AUTHORIZATION, "OAuth " + header); }
From source file:org.jets3t.service.impl.rest.httpclient.RestStorageService.java
/** * Authorizes an HTTP/S request by signing it with an HMAC signature compatible with * the S3 service and Google Storage (legacy) authorization techniques. * * The signature is added to the request as an Authorization header. * * @param httpMethod// www.j ava 2 s . c o m * the request object * @throws ServiceException */ public void authorizeHttpRequest(HttpUriRequest httpMethod, HttpContext context) throws ServiceException { if (getProviderCredentials() != null) { if (log.isDebugEnabled()) { log.debug("Adding authorization for Access Key '" + getProviderCredentials().getAccessKey() + "'."); } } else { if (log.isDebugEnabled()) { log.debug("Service has no Credential and is un-authenticated, skipping authorization"); } return; } URI uri = httpMethod.getURI(); String hostname = uri.getHost(); /* * Determine the complete URL for the S3 resource, including any S3-specific parameters. */ // Use raw-path, otherwise escaped characters are unescaped and a wrong // signature is produced String xfullUrl = uri.getPath(); String fullUrl = uri.getRawPath(); // If we are using an alternative hostname, include the hostname/bucketname in the resource path. String s3Endpoint = this.getEndpoint(); if (hostname != null && !s3Endpoint.equals(hostname)) { int subdomainOffset = hostname.lastIndexOf("." + s3Endpoint); if (subdomainOffset > 0) { // Hostname represents an S3 sub-domain, so the bucket's name is the CNAME portion fullUrl = "/" + hostname.substring(0, subdomainOffset) + fullUrl; } else { // Hostname represents a virtual host, so the bucket's name is identical to hostname fullUrl = "/" + hostname + fullUrl; } } String queryString = uri.getRawQuery(); if (queryString != null && queryString.length() > 0) { fullUrl += "?" + queryString; } // Set/update the date timestamp to the current time // Note that this will be over-ridden if an "x-amz-date" or // "x-goog-date" header is present. httpMethod.setHeader("Date", ServiceUtils.formatRfc822Date(getCurrentTimeWithOffset())); if (log.isDebugEnabled()) { log.debug("For creating canonical string, using uri: " + fullUrl); } // Generate a canonical string representing the operation. String canonicalString = null; try { canonicalString = RestUtils.makeServiceCanonicalString(httpMethod.getMethod(), fullUrl, convertHeadersToMap(httpMethod.getAllHeaders()), null, getRestHeaderPrefix(), getResourceParameterNames()); } catch (UnsupportedEncodingException e) { throw new RuntimeException(e.getMessage(), e); } if (log.isDebugEnabled()) { log.debug("Canonical string ('|' is a newline): " + canonicalString.replace('\n', '|')); } // Sign the canonical string. String signedCanonical = ServiceUtils.signWithHmacSha1(getProviderCredentials().getSecretKey(), canonicalString); // Add encoded authorization to connection as HTTP Authorization header. String authorizationString = getSignatureIdentifier() + " " + getProviderCredentials().getAccessKey() + ":" + signedCanonical; httpMethod.setHeader("Authorization", authorizationString); }
From source file:com.codeasylum.stress.api.HttpTask.java
@Override public void execute(long timeDifferential, int hostIndex, String hostId, Ouroboros ouroboros, ExchangeTransport exchangeTransport) throws IOException, ScriptInterpolationException { if (isEnabled() && ouroboros.isEnabled()) { HttpUriRequest httpRequest; ResponseCarrier responseCarrier; URI requestURI;//from w ww .j a v a 2 s . c om StringBuilder uriBuilder; String requestMimeType; String requestCharSet; String requestBody; boolean validated = true; long startTime; if ((portAttribute.getScript() == null) || (portAttribute.getScript().length() == 0)) { throw new TaskExecutionException("The %s(%s) has no http port value configured", HttpTask.class.getSimpleName(), getName()); } uriBuilder = new StringBuilder("http://").append(serverAttribute.get(this)).append(':') .append(portAttribute.get(this)).append('/').append(pathAttribute.get(this)); try { requestURI = new URI(uriBuilder.toString()); } catch (URISyntaxException uriSyntaxException) { throw new TaskExecutionException(uriSyntaxException, "The %s(%s) has been configured with a malformed URI(%s)", HttpTask.class.getSimpleName(), getName(), uriBuilder.toString()); } if ((requestMimeType = contentTypeAttribute.get(this)) != null) { int semiColonPos; if ((semiColonPos = requestMimeType.indexOf(';')) < 0) { requestCharSet = "utf-8"; } else { int equalsPos; if ((equalsPos = requestMimeType.indexOf('=', semiColonPos + 1)) <= 0) { throw new TaskExecutionException( "The %s(%s) contains an improperly formatted content type(%s)", HttpTask.class.getSimpleName(), getName(), requestMimeType); } requestCharSet = requestMimeType.substring(equalsPos + 1); requestMimeType = requestMimeType.substring(0, semiColonPos); } } else { requestMimeType = "text/plain"; requestCharSet = "utf-8"; } switch (httpMethod) { case GET: if (((requestBody = bodyAttribute.get(this)) != null) && (requestBody.length() > 0)) { throw new TaskExecutionException( "The %s(%s) uses the 'GET' method, but has been configured with body content", HttpTask.class.getSimpleName(), getName()); } httpRequest = new HttpGet(requestURI); break; case PUT: if (((requestBody = bodyAttribute.get(this)) == null) || (requestBody.length() == 0)) { throw new TaskExecutionException( "The %s(%s) uses the 'PUT' method, but has not been configured with any body content", HttpTask.class.getSimpleName(), getName()); } httpRequest = new HttpPut(requestURI); ((HttpPut) httpRequest).setEntity(new StringEntity(requestBody, requestCharSet)); break; case POST: if (((requestBody = bodyAttribute.get(this)) == null) || (requestBody.length() == 0)) { throw new TaskExecutionException( "The %s(%s) uses the 'POST' method, but has not been configured with any body content", HttpTask.class.getSimpleName(), getName()); } httpRequest = new HttpPost(requestURI); ((HttpPost) httpRequest).setEntity(new StringEntity(requestBody, requestCharSet)); break; case DELETE: if (((requestBody = bodyAttribute.get(this)) != null) && (requestBody.length() > 0)) { throw new TaskExecutionException( "The %s(%s) uses the 'DELETE' method, but has been configured with body content", HttpTask.class.getSimpleName(), getName()); } httpRequest = new HttpDelete(requestURI); break; default: throw new UnknownSwitchCaseException(httpMethod.name()); } httpRequest.setHeader("Content-Type", requestMimeType + ";charset=" + requestCharSet); startTime = System.currentTimeMillis(); try { responseCarrier = httpClient.execute(httpRequest, new ResponseHandler<ResponseCarrier>() { @Override public ResponseCarrier handleResponse(HttpResponse response) throws IOException { HttpEntity entity; Header contentTypeHeader = response.getFirstHeader("Content-Type"); String responseMimeType; String responseCharSet; if ((contentTypeHeader != null) && ((responseMimeType = contentTypeHeader.getValue()) != null)) { int semiColonPos; if ((semiColonPos = responseMimeType.indexOf(';')) < 0) { responseCharSet = "utf-8"; } else { int equalsPos; if ((equalsPos = responseMimeType.indexOf('=', semiColonPos + 1)) <= 0) { throw new TaskExecutionException( "Improperly formatted content type(%s) in response", responseMimeType); } responseCharSet = responseMimeType.substring(equalsPos + 1); responseMimeType = responseMimeType.substring(0, semiColonPos); } } else { responseMimeType = "text/plain"; responseCharSet = "utf-8"; } return new ResponseCarrier(System.currentTimeMillis(), response.getStatusLine().getStatusCode(), responseMimeType, responseCharSet, ((entity = response.getEntity()) == null) ? null : EntityUtils.toByteArray(entity)); } }); if (!regexpMap.isEmpty()) { Matcher regexpMatcher; String responseBody = (responseCarrier.getRawResponse() == null) ? null : new String(responseCarrier.getRawResponse(), responseCarrier.getResponseCharSet()); for (Map.Entry<String, String> regexpEntry : regexpMap.entrySet()) { PropertyContext.removeKeysStartingWith(regexpEntry.getKey()); if (responseBody != null) { if ((regexpMatcher = Pattern.compile( PROPERTY_EXPANDER.expand(regexpEntry.getValue(), PropertyContext.getMap())) .matcher(responseBody)).find()) { PropertyContext.put(regexpEntry.getKey(), "true"); for (int groupIndex = 0; groupIndex <= regexpMatcher.groupCount(); groupIndex++) { PropertyContext.put(regexpEntry.getKey() + '.' + groupIndex, regexpMatcher.group(groupIndex)); } } else { PropertyContext.put(regexpEntry.getKey(), "false"); } } } } if (!validationMap.isEmpty()) { for (Map.Entry<String, String> validationEntry : validationMap.entrySet()) { if (!PropertyContext.valueEquals(validationEntry.getKey(), validationEntry.getValue())) { validated = false; break; } } } if ((responseKey != null) && (responseKey.length() > 0)) { PropertyContext.put(responseKey, new String(responseCarrier.getRawResponse())); } exchangeTransport.send(new HttpExchange(validated && (responseCarrier.getResponseCode() == 200), hostId, getName(), startTime + timeDifferential, responseCarrier.getResponseTimestamp() + timeDifferential, responseCarrier.getResponseCode(), requestMimeType, requestCharSet, requestBody, responseCarrier.getResponseMimeType(), responseCarrier.getResponseCharSet(), responseCarrier.getRawResponse())); } catch (Exception exception) { exchangeTransport.send(new HttpExchange(false, hostId, getName(), startTime + timeDifferential, System.currentTimeMillis() + timeDifferential, 503, requestMimeType, requestCharSet, requestBody, "text/plain", "utf-8", StackTraceUtilities.obtainStackTraceAsString(exception).getBytes())); if (!regexpMap.isEmpty()) { for (Map.Entry<String, String> regexpEntry : regexpMap.entrySet()) { PropertyContext.removeKeysStartingWith(regexpEntry.getKey()); } } if ((responseKey != null) && (responseKey.length() > 0)) { PropertyContext.remove(responseKey); } } } }
From source file:org.jets3t.service.impl.rest.httpclient.RestStorageService.java
/** * Adds all valid metadata name and value pairs as HTTP headers to the given HTTP method. * Null metadata names are ignored, as are metadata values that are not of type string. * <p>/*from w w w.j a va 2 s . co m*/ * The metadata values are verified to ensure that keys contain only ASCII characters, * and that items are not accidentally duplicated due to use of different capitalization. * If either of these verification tests fails, an {@link org.jets3t.service.ServiceException} is thrown. * * @param httpMethod * @param metadata * @throws org.jets3t.service.ServiceException */ protected void addMetadataToHeaders(HttpUriRequest httpMethod, Map<String, Object> metadata) throws ServiceException { Map<String, Object> headersAlreadySeenMap = new HashMap<String, Object>(metadata.size()); for (Map.Entry<String, Object> entry : metadata.entrySet()) { String key = entry.getKey(); Object objValue = entry.getValue(); if (key == null) { // Ignore invalid metadata. continue; } String value = objValue.toString(); // Ensure user-supplied metadata values are compatible with the REST interface. // Key must be ASCII text, non-ASCII characters are not allowed in HTTP header names. boolean validAscii = false; UnsupportedEncodingException encodingException = null; try { byte[] asciiBytes = key.getBytes("ASCII"); byte[] utf8Bytes = key.getBytes("UTF-8"); validAscii = Arrays.equals(asciiBytes, utf8Bytes); } catch (UnsupportedEncodingException e) { // Shouldn't ever happen encodingException = e; } if (!validAscii) { String message = "User metadata name is incompatible with the S3 REST interface, " + "only ASCII characters are allowed in HTTP headers: " + key; if (encodingException == null) { throw new ServiceException(message); } else { throw new ServiceException(message, encodingException); } } // Fail early if user-supplied metadata cannot be represented as valid HTTP headers, // rather than waiting for a SignatureDoesNotMatch error. // NOTE: These checks are very much incomplete. if (value.indexOf('\n') >= 0 || value.indexOf('\r') >= 0) { throw new ServiceException("The value of metadata item " + key + " cannot be represented as an HTTP header for the REST S3 interface: " + value); } // Ensure each AMZ header is uniquely identified according to the lowercase name. String duplicateValue = (String) headersAlreadySeenMap.get(key.toLowerCase(Locale.US)); if (duplicateValue != null && !duplicateValue.equals(value)) { throw new ServiceException( "HTTP header name occurs multiple times in request with different values, " + "probably due to mismatched capitalization when setting metadata names. " + "Duplicate metadata name: '" + key + "', All metadata: " + metadata); } // PUT: don't set the 'Content-Length' header or http-client-4 will // raise an exception 'already set'. if (!httpMethod.getMethod().equalsIgnoreCase("PUT") || !SS3Object.METADATA_HEADER_CONTENT_LENGTH.equalsIgnoreCase(key)) { httpMethod.setHeader(key, value); } headersAlreadySeenMap.put(key.toLowerCase(Locale.US), value); } }
From source file:net.tsz.afinal.http.HttpHandler.java
private void makeRequestWithRetries(HttpUriRequest request) throws IOException { if (isResume && targetUrl != null) { File downloadFile = new File(targetUrl); long fileLen = 0; if (downloadFile.isFile() && downloadFile.exists()) { fileLen = downloadFile.length(); }// w w w . j av a2s . c o m if (fileLen > 0) request.setHeader("RANGE", "bytes=" + fileLen + "-"); } boolean retry = true; IOException cause = null; HttpRequestRetryHandler retryHandler = client.getHttpRequestRetryHandler();//? while (retry) { try { if (isCancelled()) { return; } //POST:?;GET:? String requestUrl = request.getURI().toString(); String requestMethod = request.getMethod(); ZLogger.d(String.format("<%d><%s> %s", executionCount, requestMethod, requestUrl)); for (Header header : request.getAllHeaders()) { ZLogger.d(String.format("<%s>:<%s>", header.getName(), header.getValue())); } //??url StringBuilder requestParams = new StringBuilder(); if (requestMethod.equals(POST)) { HttpEntityEnclosingRequestBase requestBase = (HttpEntityEnclosingRequestBase) request; if (requestBase != null) { HttpEntity entity = requestBase.getEntity(); if (entity != null) { InputStream is = entity.getContent(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line = null; try { while ((line = reader.readLine()) != null) { // sb.append(line + "/n"); // Log.d("Nat: makeRequestWithRetries.request.Params.line", line); requestParams.append(line); } } catch (IOException e) { e.printStackTrace(); ZLogger.ef(e.toString()); } finally { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } // byte[] paramsArray = EntityUtils.toByteArray(entity); // String paramsStr = EntityUtils.toString(entity, "UTF-8"); // Log.d("Nat: makeRequestWithRetries.request.Params(2)", paramsStr); // Log.d("Nat: makeRequestWithRetries.request.Params(3)", EntityUtils.toString(entity)); } // Log.d("Nat: makeRequestWithRetries.request.Params(RAW)", requestParams.toString()); } // HttpResponse response = client.execute(request, context); // for(Header header : response.getAllHeaders()){ // Log.d("Nat", String.format(" makeRequestWithRetries.respoonse.header <%s><%s>", header.getName(), header.getValue())); // } if (isCancelled()) { ZLogger.d("Nat: makeRequestWithRetries", "request caneled."); return; } //POST:?;GET:? request.getRequestLine();//GET ZLogger.d(request.getRequestLine().toString()); /*if (request.getMethod().equals("post")) { HttpParams params = request.getParams(); params.setParameter(NetFactory.CLIENTSESSION, ""); request.snetParams(params); }*/ //?????() //executionCount < 1,????? if (response.containsHeader("needLogin")/* && executionCount < 1*/) { //?url?JSSIONID??cookie. //?(?),sessionId String newSid = MfhLoginService.get().doLogin(); if (newSid == null) { //TODO //,? // Intent intent = new Intent(Constants.ACTION_REDIRECT_TO_LOGIN_H5); // BizApplication.getAppContext().sendBroadcast(intent); // break; } else { String cookie = String.format("%s=%s", FinalHttp.KEY_JSESSIONID, newSid); request.addHeader(FinalHttp.HEADER_SET_COOKIE, cookie); request.addHeader(FinalHttp.HEADER_COOKIE, cookie); request.addHeader(FinalHttp.HEADER_cookie, cookie); // ? // MsgBridgeUtil.register(); if (requestMethod.equals(POST)) { // //EntityJSSIONID String newParams = replaceParam(requestParams.toString(), JSESSIONID, newSid); // HttpEntity entity = new StringEntity(newParams); HttpEntity entity = convertToAjaxParams(newParams).getEntity(); ((HttpEntityEnclosingRequestBase) request).setEntity(entity); } else if (requestMethod.equals(GET)) { //URLJSSIONID String newRequestUrl = replaceParam(requestUrl, JSESSIONID, newSid); // newRequestUrl = replaceParam(newRequestUrl, "lastupdate", "0"); URI uri = new URI(newRequestUrl); // Log.d("Nat: makeRequestWithRetries.autoLogin.URI", uri.toString()); // HttpEntityEnclosingRequestBase requestFact = (HttpEntityEnclosingRequestBase)request; // requestFact.setURI(uri); ((HttpEntityEnclosingRequestBase) request).setURI(uri); } } //TODO,? retry = (++executionCount <= MAX_RETRY_TIMES) || retryHandler.retryRequest(new IOException("Exception"), executionCount, context); // ZLogger.d(String.format("%s %d", retry ? "?" : "??", executionCount)); if (retry) { continue; } } //? handleResponse(response); return; } catch (UnknownHostException e) { ZLogger.e("UnknownHostException:" + e.toString()); publishProgress(UPDATE_FAILURE, e, "unknownHostExceptioncan't resolve host"); return; } catch (IOException e) { ZLogger.e("IOException: " + e.toString()); cause = e; retry = retryHandler.retryRequest(cause, ++executionCount, context); publishProgress(UPDATE_FAILURE, e, "unknownHostExceptioncan't resolve host"); } catch (NullPointerException e) { if (e != null) { ZLogger.e("NullPointerException: " + e.toString()); // here's a bug in HttpClient 4.0.x that on some occasions causes // DefaultRequestExecutor to throw an NPE, see // http://code.google.com/p/android/issues/detail?id=5255 cause = new IOException("NPE in HttpClient: " + e.getMessage()); retry = retryHandler.retryRequest(cause, ++executionCount, context); } else { ZLogger.e("NullPointerException: e is null"); } publishProgress(UPDATE_FAILURE, e, "unknownHostExceptioncan't resolve host"); } catch (Exception e) { ZLogger.e("Exception: " + e.toString()); cause = new IOException("Unhandled Exception" + e.getMessage()); retry = retryHandler.retryRequest(cause, ++executionCount, context); publishProgress(UPDATE_FAILURE, e, "unknownHostExceptioncan't resolve host"); } } // cleaned up to throw IOException if (cause != null) { throw cause; } // else{ // //TODO // throw new IOException(""); // } }
From source file:org.apache.asterix.test.aql.TestExecutor.java
public InputStream executeQueryService(String str, OutputFormat fmt, String url, List<CompilationUnit.Parameter> params, boolean jsonEncoded) throws Exception { setFormatParam(params, fmt);/*from www . j a va 2s. co m*/ HttpUriRequest method = jsonEncoded ? constructPostMethodJson(str, url, "statement", params) : constructPostMethodUrl(str, url, "statement", params); // Set accepted output response type method.setHeader("Accept", OutputFormat.CLEAN_JSON.mimeType()); HttpResponse response = executeHttpRequest(method); return response.getEntity().getContent(); }
From source file:org.nuxeo.ecm.automation.client.jaxrs.impl.HttpConnector.java
protected Object execute(Request request, HttpUriRequest httpReq) throws Exception { for (Map.Entry<String, String> entry : request.entrySet()) { httpReq.setHeader(entry.getKey(), entry.getValue()); }/* w ww .j ava2s. co m*/ HttpResponse resp = executeRequestWithTimeout(httpReq); HttpEntity entity = resp.getEntity(); int status = resp.getStatusLine().getStatusCode(); if (entity == null) { if (status < 400) { return null; } throw new RemoteException(status, "ServerError", "Server Error", (Throwable) null); } Header ctypeHeader = entity.getContentType(); if (ctypeHeader == null) { // handle broken responses with no ctype if (status != 200) { // this may happen when login failed throw new RemoteException(status, "ServerError", "Server Error", (Throwable) null); } return null; // cannot handle responses with no ctype } String ctype = ctypeHeader.getValue(); String disp = null; Header[] hdisp = resp.getHeaders("Content-Disposition"); if (hdisp != null && hdisp.length > 0) { disp = hdisp[0].getValue(); } return request.handleResult(status, ctype, disp, entity.getContent()); }
From source file:org.opencastproject.kernel.security.TrustedHttpClientImpl.java
@Override public HttpResponse execute(HttpUriRequest httpUriRequest, int connectionTimeout, int socketTimeout) throws TrustedHttpClientException { HttpClient httpClient = makeHttpClient(); httpClient.getParams().setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectionTimeout); // Add the request header to elicit a digest auth response httpUriRequest.setHeader(REQUESTED_AUTH_HEADER, DIGEST_AUTH); httpUriRequest.setHeader(SecurityConstants.AUTHORIZATION_HEADER, "true"); if (serviceRegistry != null && serviceRegistry.getCurrentJob() != null) httpUriRequest.setHeader(CURRENT_JOB_HEADER, Long.toString(serviceRegistry.getCurrentJob().getId())); // If a security service has been set, use it to pass the current security context on logger.debug("Adding security context to request"); Organization organization = securityService.getOrganization(); if (organization != null) { httpUriRequest.setHeader(SecurityConstants.ORGANIZATION_HEADER, organization.getId()); User currentUser = securityService.getUser(); if (currentUser != null) httpUriRequest.setHeader(SecurityConstants.USER_HEADER, currentUser.getUserName()); }//from w w w.java 2 s . co m if ("GET".equalsIgnoreCase(httpUriRequest.getMethod()) || "HEAD".equalsIgnoreCase(httpUriRequest.getMethod())) { // Set the user/pass UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, pass); httpClient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds); // Run the request (the http client handles the multiple back-and-forth requests) HttpResponse response = null; try { response = httpClient.execute(httpUriRequest); responseMap.put(response, httpClient); return response; } catch (IOException e) { // close the http connection(s) httpClient.getConnectionManager().shutdown(); throw new TrustedHttpClientException(e); } } // HttpClient doesn't handle the request dynamics for other verbs (especially when sending a streamed multipart // request), so we need to handle the details of the digest auth back-and-forth manually manuallyHandleDigestAuthentication(httpUriRequest, httpClient); HttpResponse response = null; try { response = httpClient.execute(httpUriRequest); if (nonceTimeoutRetries > 0 && hadNonceTimeoutResponse(response)) { httpClient.getConnectionManager().shutdown(); response = retryAuthAndRequestAfterNonceTimeout(httpUriRequest, response); } responseMap.put(response, httpClient); return response; } catch (Exception e) { // if we have a response, remove it from the map if (response != null) { responseMap.remove(response); } // close the http connection(s) httpClient.getConnectionManager().shutdown(); throw new TrustedHttpClientException(e); } }
From source file:synapticloop.b2.request.BaseB2Request.java
/** * Set the headers safely, go through the headers Map and add them to the http * request with properly encode values. If they already exist on the http * request, it will be ignored./*from w ww . j av a2 s.com*/ * * To override what headers are set, this should be done in the constructor * of the base request object. * * @param request The HTTP request to set the headers on * * @throws B2ApiException if there was an error setting the headers */ protected void setHeaders(HttpUriRequest request) throws B2ApiException { for (String headerKey : requestHeaders.keySet()) { if (!request.containsHeader(headerKey)) { final String headerValue = requestHeaders.get(headerKey); LOGGER.trace("Setting header '" + headerKey + "' to '" + headerValue + "'."); request.setHeader(headerKey, headerValue); } else { LOGGER.warn("Ignore duplicate header " + headerKey); } } }