List of usage examples for org.apache.http.client.methods HttpUriRequest setHeader
void setHeader(String str, String str2);
From source file:org.jets3t.service.impl.rest.httpclient.RestStorageService.java
/** * Adds the provided request headers to the connection. * * @param httpMethod//from w w w . j ava 2 s. c o m * the connection object * @param requestHeaders * the request headers to add as name/value pairs. */ protected void addRequestHeadersToConnection(HttpUriRequest httpMethod, Map<String, Object> requestHeaders) { if (requestHeaders != null) { for (Map.Entry<String, Object> entry : requestHeaders.entrySet()) { String key = entry.getKey(); String value = entry.getValue().toString(); httpMethod.setHeader(key, value); if (log.isDebugEnabled()) { log.debug("Added request header to connection: " + key + "=" + value); } } } }
From source file:cn.com.loopj.android.http.AsyncHttpClient.java
/** * Puts a new request in queue as a new thread in pool to be executed * * @param client HttpClient to be used for request, can differ in single requests * @param contentType MIME body type, for POST and PUT requests, may be null * @param context Context of Android application, to hold the reference of request * @param httpContext HttpContext in which the request will be executed * @param responseHandler ResponseHandler or its subclass to put the response into * @param uriRequest instance of HttpUriRequest, which means it must be of HttpDelete, * HttpPost, HttpGet, HttpPut, etc. * @return RequestHandle of future request process *//*from w w w . j a va2s . c om*/ protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler, Context context) { if (uriRequest == null) { throw new IllegalArgumentException("HttpUriRequest must not be null"); } if (responseHandler == null) { throw new IllegalArgumentException("ResponseHandler must not be null"); } if (responseHandler.getUseSynchronousMode() && !responseHandler.getUsePoolThread()) { throw new IllegalArgumentException( "Synchronous ResponseHandler used in AsyncHttpClient. You should create your response handler in a looper thread or use SyncHttpClient instead."); } if (contentType != null) { if (uriRequest instanceof HttpEntityEnclosingRequestBase && ((HttpEntityEnclosingRequestBase) uriRequest).getEntity() != null && uriRequest.containsHeader(HEADER_CONTENT_TYPE)) { log.w(LOG_TAG, "Passed contentType will be ignored because HttpEntity sets content type"); } else { uriRequest.setHeader(HEADER_CONTENT_TYPE, contentType); } } responseHandler.setRequestHeaders(uriRequest.getAllHeaders()); responseHandler.setRequestURI(uriRequest.getURI()); AsyncHttpRequest request = newAsyncHttpRequest(client, httpContext, uriRequest, contentType, responseHandler, context); threadPool.submit(request); RequestHandle requestHandle = new RequestHandle(request); if (context != null) { List<RequestHandle> requestList; // Add request to request map synchronized (requestMap) { requestList = requestMap.get(context); if (requestList == null) { requestList = Collections.synchronizedList(new LinkedList<RequestHandle>()); requestMap.put(context, requestList); } } requestList.add(requestHandle); Iterator<RequestHandle> iterator = requestList.iterator(); while (iterator.hasNext()) { if (iterator.next().shouldBeGarbageCollected()) { iterator.remove(); } } } return requestHandle; }
From source file:org.jasig.portlet.proxy.service.web.HttpContentServiceImpl.java
protected HttpUriRequest getHttpRequest(HttpContentRequestImpl proxyRequest, PortletRequest request) { final HttpUriRequest httpRequest; // if this is a form request, we may need to use a POST or add form parameters if (proxyRequest.isForm()) { // handle POST form request final Map<String, IFormField> params = proxyRequest.getParameters(); if ("POST".equalsIgnoreCase(proxyRequest.getMethod())) { final List<NameValuePair> pairs = new ArrayList<NameValuePair>(); for (Map.Entry<String, IFormField> param : params.entrySet()) { for (String value : param.getValue().getValues()) { if (value != null) { pairs.add(new BasicNameValuePair(param.getKey(), value)); }/*from w w w . ja va2 s.c o m*/ } } // construct a new POST request and set the form data try { httpRequest = new HttpPost(proxyRequest.getProxiedLocation()); if (pairs.size() > 0) { ((HttpPost) httpRequest).setEntity(new UrlEncodedFormEntity(pairs, "UTF-8")); } } catch (UnsupportedEncodingException e) { log.error("Failed to encode form parameters", e); throw new RuntimeException(e); } } // handle GET form requests else { try { // build a URL including any passed form parameters final URIBuilder builder = new URIBuilder(proxyRequest.getProxiedLocation()); for (Map.Entry<String, IFormField> param : params.entrySet()) { for (String value : param.getValue().getValues()) { builder.addParameter(param.getKey(), value); } } final URI uri = builder.build(); httpRequest = new HttpGet(uri); } catch (URISyntaxException e) { log.error("Failed to build URI for proxying", e); throw new RuntimeException(e); } } } // not a form, simply a normal get request else { log.debug("Submitting a GET request to proxied location [{}]", proxyRequest.getProxiedLocation()); httpRequest = new HttpGet(proxyRequest.getProxiedLocation()); } // set any configured request headers for (Map.Entry<String, String> header : proxyRequest.getHeaders().entrySet()) { httpRequest.setHeader(header.getKey(), header.getValue()); } return httpRequest; }
From source file:com.joyent.manta.http.EncryptionHttpHelper.java
/** * Calculates the skip bytes and plaintext length for a encrypted ranged * request./*from w w w . ja v a2 s . c o m*/ * * @param request source request that hasn't been made yet * @param requestHeaders headers passed to the request * @return a {@link Long} array containing two elements: skip bytes, plaintext length * @throws IOException thrown when we fail making an additional HEAD request */ private PlaintextByteRangePosition calculateSkipBytesAndPlaintextLength(final HttpUriRequest request, final MantaHttpHeaders requestHeaders) throws IOException { final Long initialSkipBytes; Long plaintextRangeLength = 0L; final long[] plaintextRanges = byteRangeAsNullSafe(requestHeaders.getByteRange(), this.cipherDetails); final long plaintextStart = plaintextRanges[0]; final long plaintextEnd = plaintextRanges[1]; final long binaryStartPositionInclusive; final long binaryEndPositionInclusive; final boolean negativeEndRequest = plaintextEnd < 0; // We have been passed a request in the form of something like: bytes=-50 if (plaintextStart == 0 && negativeEndRequest) { /* Since we don't know the size of the object, there is no way * for us to know what the value of objectSize - N is. So we * do a HEAD request and discover the plaintext object size * and the size of the ciphertext. This allows us to have * the information needed to do a proper range request. */ final String path = request.getURI().getPath(); // Forward on all headers to the HEAD request final HttpHead head = getRequestFactory().head(path); MantaHttpRequestFactory.addHeaders(head, request.getAllHeaders()); head.removeHeaders(HttpHeaders.RANGE); HttpResponse headResponse = super.executeAndCloseRequest(head, "HEAD {} response [{}] {} "); final MantaHttpHeaders headers = new MantaHttpHeaders(headResponse.getAllHeaders()); MantaObjectResponse objectResponse = new MantaObjectResponse(path, headers); /* We make the actual GET request's success dependent on the * object not changing since we did the HEAD request. */ request.setHeader(HttpHeaders.IF_MATCH, objectResponse.getEtag()); request.setHeader(HttpHeaders.IF_UNMODIFIED_SINCE, objectResponse.getHeaderAsString(HttpHeaders.LAST_MODIFIED)); Long ciphertextSize = objectResponse.getContentLength(); Validate.notNull(ciphertextSize, "Manta should always return a content-size"); // We query the response object for multiple properties that will // give us the plaintext size. If not possible, this will error. long fullPlaintextSize = HttpHelper.attemptToFindPlaintextSize(objectResponse, ciphertextSize, this.cipherDetails); // Since plaintextEnd is a negative value - this will be set to // the number of bytes before the end of the file (in plaintext) initialSkipBytes = plaintextEnd + fullPlaintextSize; // calculates the ciphertext byte range final ByteRangeConversion computedRanges = this.cipherDetails.translateByteRange(initialSkipBytes, fullPlaintextSize - 1); // We only use the ciphertext start position, because we already // have the position of the end of the ciphertext (eg content-length) binaryStartPositionInclusive = computedRanges.getCiphertextStartPositionInclusive(); binaryEndPositionInclusive = ciphertextSize; // This is the typical case like: bytes=3-44 } else { long scaledPlaintextEnd = plaintextEnd; // interpret maximum plaintext value as unbounded end if (plaintextEnd == cipherDetails.getMaximumPlaintextSizeInBytes()) { scaledPlaintextEnd--; } // calculates the ciphertext byte range final ByteRangeConversion computedRanges = this.cipherDetails.translateByteRange(plaintextStart, scaledPlaintextEnd); binaryStartPositionInclusive = computedRanges.getCiphertextStartPositionInclusive(); initialSkipBytes = computedRanges.getPlaintextBytesToSkipInitially() + computedRanges.getCiphertextStartPositionInclusive(); if (computedRanges.getCiphertextEndPositionInclusive() > 0) { binaryEndPositionInclusive = computedRanges.getCiphertextEndPositionInclusive(); } else { binaryEndPositionInclusive = 0; } plaintextRangeLength = (scaledPlaintextEnd - plaintextStart) + 1; } // We don't know the ending position if (binaryEndPositionInclusive == 0) { requestHeaders.setRange(String.format("bytes=%d-", binaryStartPositionInclusive)); } else { requestHeaders.setRange( String.format("bytes=%d-%d", binaryStartPositionInclusive, binaryEndPositionInclusive)); } // Range in the form of 50-, so we don't know the actual plaintext length if (plaintextEnd >= cipherDetails.getMaximumPlaintextSizeInBytes()) { plaintextRangeLength = 0L; } return new PlaintextByteRangePosition().setInitialPlaintextSkipBytes(initialSkipBytes) .setPlaintextRangeLength(plaintextRangeLength).setPlaintextStart(plaintextStart) .setPlaintextEnd(plaintextEnd); }
From source file:com.amytech.android.library.utils.asynchttp.AsyncHttpClient.java
/** * Puts a new request in queue as a new thread in pool to be executed * * @param client/*from w ww. j ava 2s.c o m*/ * HttpClient to be used for request, can differ in single * requests * @param contentType * MIME body type, for POST and PUT requests, may be null * @param context * Context of Android application, to hold the reference of * request * @param httpContext * HttpContext in which the request will be executed * @param responseHandler * ResponseHandler or its subclass to put the response into * @param uriRequest * instance of HttpUriRequest, which means it must be of * HttpDelete, HttpPost, HttpGet, HttpPut, etc. * @return RequestHandle of future request process */ protected RequestHandle sendRequest(DefaultHttpClient client, HttpContext httpContext, HttpUriRequest uriRequest, String contentType, ResponseHandlerInterface responseHandler, Context context) { if (uriRequest == null) { throw new IllegalArgumentException("HttpUriRequest must not be null"); } if (responseHandler == null) { throw new IllegalArgumentException("ResponseHandler must not be null"); } if (responseHandler.getUseSynchronousMode() && !responseHandler.getUsePoolThread()) { throw new IllegalArgumentException( "Synchronous ResponseHandler used in AsyncHttpClient. You should create your response handler in a looper thread or use SyncHttpClient instead."); } if (contentType != null) { if (uriRequest instanceof HttpEntityEnclosingRequestBase && ((HttpEntityEnclosingRequestBase) uriRequest).getEntity() != null && uriRequest.containsHeader(HEADER_CONTENT_TYPE)) { Log.w(LOG_TAG, "Passed contentType will be ignored because HttpEntity sets content type"); } else { uriRequest.setHeader(HEADER_CONTENT_TYPE, contentType); } } responseHandler.setRequestHeaders(uriRequest.getAllHeaders()); responseHandler.setRequestURI(uriRequest.getURI()); AsyncHttpRequest request = newAsyncHttpRequest(client, httpContext, uriRequest, contentType, responseHandler, context); threadPool.submit(request); RequestHandle requestHandle = new RequestHandle(request); if (context != null) { List<RequestHandle> requestList; // Add request to request map synchronized (requestMap) { requestList = requestMap.get(context); if (requestList == null) { requestList = Collections.synchronizedList(new LinkedList<RequestHandle>()); requestMap.put(context, requestList); } } requestList.add(requestHandle); Iterator<RequestHandle> iterator = requestList.iterator(); while (iterator.hasNext()) { if (iterator.next().shouldBeGarbageCollected()) { iterator.remove(); } } } return requestHandle; }
From source file:org.jets3t.service.impl.rest.httpclient.RestStorageService.java
/** * Creates an {@link org.apache.http.HttpRequest} object to handle a particular connection method. * * @param method// w w w. ja va 2s . co m * the HTTP method/connection-type to use, must be one of: PUT, HEAD, GET, DELETE * @param bucketName * the bucket's name * @param objectKey * the object's key name, may be null if the operation is on a bucket only. * @return * the HTTP method object used to perform the request * * @throws org.jets3t.service.ServiceException */ protected HttpUriRequest setupConnection(HTTP_METHOD method, String bucketName, String objectKey, Map<String, String> requestParameters) throws ServiceException { if (bucketName == null) { throw new ServiceException("Cannot connect to S3 Service with a null path"); } boolean disableDnsBuckets = this.getDisableDnsBuckets(); String endPoint = this.getEndpoint(); String hostname = ServiceUtils.generateS3HostnameForBucket(bucketName, disableDnsBuckets, endPoint); // Allow for non-standard virtual directory paths on the server-side String virtualPath = this.getVirtualPath(); // Determine the resource string (ie the item's path in S3, including the bucket name) String resourceString = "/"; if (hostname.equals(endPoint) && bucketName.length() > 0) { resourceString += bucketName; } if (objectKey != null) { resourceString += "/" + RestUtils.encodeUrlString(objectKey); } // resourceString += (objectKey != null ? RestUtils.encodeUrlString(objectKey) : ""); // Construct a URL representing a connection for the S3 resource. String url = null; if (isHttpsOnly()) { int securePort = this.getHttpsPort(); url = "https://" + hostname + ":" + securePort + virtualPath + resourceString; } else { int insecurePort = this.getHttpPort(); url = "http://" + hostname + ":" + insecurePort + virtualPath + resourceString; } if (log.isDebugEnabled()) { log.debug("S3 URL: " + url); } // Add additional request parameters to the URL for special cases (eg ACL operations) url = addRequestParametersToUrlPath(url, requestParameters); HttpUriRequest httpMethod = null; if (HTTP_METHOD.PUT.equals(method)) { httpMethod = new HttpPut(url); } else if (HTTP_METHOD.POST.equals(method)) { httpMethod = new HttpPost(url); } else if (HTTP_METHOD.HEAD.equals(method)) { httpMethod = new HttpHead(url); } else if (HTTP_METHOD.GET.equals(method)) { httpMethod = new HttpGet(url); } else if (HTTP_METHOD.DELETE.equals(method)) { httpMethod = new HttpDelete(url); } else { throw new IllegalArgumentException("Unrecognised HTTP method name: " + method); } // Set mandatory Request headers. if (httpMethod.getFirstHeader("Date") == null) { httpMethod.setHeader("Date", ServiceUtils.formatRfc822Date(getCurrentTimeWithOffset())); } return httpMethod; }
From source file:com.llkj.cm.restfull.network.NetworkConnection.java
private static NetworkConnectionResult retrieveResponseFromService(final String url, final int method, final Map<String, String> parameters, final ArrayList<Header> headers, final boolean isGzipEnabled, final String userAgent, final String postText, final ArrayList<String> previousUrlList, int connectionTimeout, int soTimeout) throws IllegalStateException, IOException, URISyntaxException, RestClientException { // Get the request URL if (url == null) { if (LogConfig.DP_ERROR_LOGS_ENABLED) { Log.e(LOG_TAG, "retrieveResponseFromService - Compulsory Parameter : request URL has not been set"); }/* ww w.j a v a 2 s. co m*/ throw new CompulsoryParameterException("Request URL has not been set"); } if (LogConfig.DP_DEBUG_LOGS_ENABLED) { Log.d(LOG_TAG, "retrieveResponseFromService - Request url : " + url); } // Get the request method if (method != METHOD_GET && method != METHOD_POST && method != METHOD_PUT && method != METHOD_DELETE) { if (LogConfig.DP_ERROR_LOGS_ENABLED) { Log.e(LOG_TAG, "retrieveResponseFromService - Request method must be METHOD_GET, METHOD_POST, METHOD_PUT or METHOD_DELETE"); } throw new IllegalArgumentException( "retrieveResponseFromService - Request method must be METHOD_GET, METHOD_POST, METHOD_PUT or METHOD_DELETE"); } if (LogConfig.DP_DEBUG_LOGS_ENABLED) { Log.d(LOG_TAG, "retrieveResponseFromService - Request method : " + method); } // Get the request parameters if (LogConfig.DP_DEBUG_LOGS_ENABLED) { Log.d(LOG_TAG, "retrieveResponseFromService - Request parameters (number) : " + ((parameters != null) ? parameters.size() : "")); } // Get the request headers if (LogConfig.DP_DEBUG_LOGS_ENABLED) { Log.d(LOG_TAG, "retrieveResponseFromService - Request headers (number) : " + ((headers != null) ? headers.size() : "")); } // Create the Request final AndroidHttpClient client = AndroidHttpClient .newInstance(userAgent != null ? userAgent : sDefaultUserAgent); if (connectionTimeout != -1) { HttpConnectionParams.setConnectionTimeout(client.getParams(), connectionTimeout); } if (soTimeout != -1) { HttpConnectionParams.setSoTimeout(client.getParams(), soTimeout); } if (LogConfig.DP_DEBUG_LOGS_ENABLED) { Log.d(LOG_TAG, "retrieveResponseFromService - Request user agent : " + userAgent); } try { HttpUriRequest request = null; switch (method) { case METHOD_GET: case METHOD_DELETE: { final StringBuffer sb = new StringBuffer(); sb.append(url); // Add the parameters to the GET url if any if (parameters != null && !parameters.isEmpty()) { sb.append("&"); final ArrayList<String> keyList = new ArrayList<String>(parameters.keySet()); final int keyListLength = keyList.size(); for (int i = 0; i < keyListLength; i++) { final String key = keyList.get(i); sb.append(URLEncoder.encode(key, "UTF-8")); sb.append("="); sb.append(URLEncoder.encode(parameters.get(key), "UTF-8")); sb.append("&"); } } if (LogConfig.DP_INFO_LOGS_ENABLED) { Log.i(LOG_TAG, "retrieveResponseFromService - GET Request - complete URL with parameters if any : "); final String completeUrl = sb.toString(); int pos = 0; int dumpLength = completeUrl.length(); while (pos < dumpLength) { Log.i(LOG_TAG, completeUrl.substring(pos, Math.min(dumpLength - 1, pos + 120))); pos = pos + 120; } } final URI uri = new URI(sb.toString()); if (method == METHOD_GET) { request = new HttpGet(uri); } else if (method == METHOD_DELETE) { request = new HttpDelete(uri); } break; } case METHOD_POST: case METHOD_PUT: { final URI uri = new URI(url); if (method == METHOD_POST) { request = new HttpPost(uri); } else if (method == METHOD_PUT) { request = new HttpPut(uri); } // Add the parameters to the POST request if any if (parameters != null && !parameters.isEmpty()) { final List<NameValuePair> postRequestParameters = new ArrayList<NameValuePair>(); final ArrayList<String> keyList = new ArrayList<String>(parameters.keySet()); final int keyListLength = keyList.size(); for (int i = 0; i < keyListLength; i++) { final String key = keyList.get(i); postRequestParameters.add(new BasicNameValuePair(key, parameters.get(key))); } if (LogConfig.DP_INFO_LOGS_ENABLED) { Log.i(LOG_TAG, "retrieveResponseFromService - POST Request - parameters list (key => value) : "); final int postRequestParametersLength = postRequestParameters.size(); for (int i = 0; i < postRequestParametersLength; i++) { final NameValuePair nameValuePair = postRequestParameters.get(i); Log.i(LOG_TAG, "- " + nameValuePair.getName() + " => " + nameValuePair.getValue()); } } request.setHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded"); if (method == METHOD_POST) { ((HttpPost) request).setEntity(new UrlEncodedFormEntity(postRequestParameters, "UTF-8")); } else if (method == METHOD_PUT) { ((HttpPut) request).setEntity(new UrlEncodedFormEntity(postRequestParameters, "UTF-8")); } } else if (null != postText) { // Add post text (send xml // for // example) if (method == METHOD_POST) { ((HttpPost) request).setEntity(new StringEntity(postText)); } else if (method == METHOD_PUT) { ((HttpPut) request).setEntity(new StringEntity(postText)); } } break; } default: { if (LogConfig.DP_ERROR_LOGS_ENABLED) { Log.e(LOG_TAG, "retrieveResponseFromService - Request method must be METHOD_GET, METHOD_POST, METHOD_PUT or METHOD_DELETE"); } throw new IllegalArgumentException( "retrieveResponseFromService - Request method must be METHOD_GET, METHOD_POST, METHOD_PUT or METHOD_DELETE"); } } // Activate the gzip compression if asked if (isGzipEnabled) { AndroidHttpClient.modifyRequestToAcceptGzipResponse(request); } if (LogConfig.DP_INFO_LOGS_ENABLED) { Log.i(LOG_TAG, "retrieveResponseFromService - Request - headers list (name => value) : "); final HeaderIterator iterator = request.headerIterator(); while (iterator.hasNext()) { final Header header = iterator.nextHeader(); Log.i(LOG_TAG, "- " + header.getName() + " => " + header.getValue()); } } // Add the request headers if any if (headers != null && !headers.isEmpty()) { final int headersLength = headers.size(); for (int i = 0; i < headersLength; i++) { request.addHeader(headers.get(i)); } } // Launch the request String result = null; if (LogConfig.DP_DEBUG_LOGS_ENABLED) { Log.d(LOG_TAG, "retrieveResponseFromService - Executing the request"); } final HttpResponse response = client.execute(request); // Get the response status final StatusLine status = response.getStatusLine(); if (LogConfig.DP_DEBUG_LOGS_ENABLED) { Log.d(LOG_TAG, "retrieveResponseFromService - Response status : " + status.getStatusCode()); } final int statusCode = status.getStatusCode(); if (statusCode != HttpStatus.SC_OK) { if (LogConfig.DP_ERROR_LOGS_ENABLED) { Log.e(LOG_TAG, "retrieveResponseFromService - Invalid response from server : " + status.toString()); } if (statusCode == HttpStatus.SC_MOVED_TEMPORARILY) { final Header newLocation = response.getFirstHeader("Location"); if (LogConfig.DP_INFO_LOGS_ENABLED) { Log.i(LOG_TAG, "retrieveResponseFromService - New location : " + newLocation.getValue()); } NewLocation.noticeNewLocation(newLocation.getValue(), url); // throw new RestClientException("New location : " + newLocation, newLocation.getValue()); } else if (statusCode == HttpStatus.SC_MOVED_PERMANENTLY) { if (method == METHOD_GET) { final String newUrl = response.getHeaders("Location")[0].getValue(); if (!previousUrlList.contains(newUrl)) { Log.d(LOG_TAG, "retrieveResponseFromService - Url moved permanently - Trying the new url : " + newUrl); previousUrlList.add(newUrl); return retrieveResponseFromService(newUrl, method, parameters, headers, isGzipEnabled, userAgent, postText); } else { // It's an url already checked. We are in a loop. So let's throw an Exception throw new RestClientException("Moved permanently - Loop detected", statusCode); } } else { throw new RestClientException("Invalid response from server : ", statusCode); } } else { throw new RestClientException("Invalid response from server : ", statusCode); } } // Get the response entity final HttpEntity entity = response.getEntity(); final Header contentEncoding = response.getFirstHeader("Content-Encoding"); if (entity != null) { result = convertStreamToString(entity.getContent(), contentEncoding != null && contentEncoding.getValue().equalsIgnoreCase("gzip"), method, (int) entity.getContentLength()); } if (LogConfig.DP_INFO_LOGS_ENABLED) { Log.i(LOG_TAG, "retrieveResponseFromService - Result from webservice : " + result); } return new NetworkConnectionResult(statusCode, response.getAllHeaders(), result); } finally { client.close(); } }
From source file:com.twitter.hbc.httpclient.auth.OAuth1.java
@Override public void signRequest(HttpUriRequest request, String postParams) { // 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 = 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);//from ww w. jav a 2 s. c om } 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.normalize(request.getURI().getScheme(), request.getURI().getHost(), port, request.getMethod().toUpperCase(), request.getURI().getPath(), javaParams, oAuth1Params); String signature; try { signature = signer.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.soyatec.windowsazure.management.ServiceManagementRest.java
private String upgradeDeployment(HttpUriRequest request, UpgradeConfiguration configuration, AsyncResultCallback callback) {//from w w w. ja v a2s.co m configuration.validate(); StringBuilder buf = new StringBuilder(); buf.append("<UpgradeDeployment xmlns=\"http://schemas.microsoft.com/windowsazure\">"); buf.append("<Mode>" + configuration.getMode().getLiteral() + "</Mode>"); buf.append("<PackageUrl>" + configuration.getPackageBlobUrl() + "</PackageUrl>"); String content = ""; if (configuration.getConfigurationFileUrl() != null) content = readBase64(configuration.getConfigurationFileUrl()); else if (configuration.getConfigurationFileStream() != null) { try { content = readBase64(configuration.getConfigurationFileStream().getBytes()); } catch (IOException e) { throw new StorageException(e); } } buf.append("<Configuration>" + content // readBase64(configuration.getConfigurationFileUrl()) + "</Configuration>"); buf.append("<Label>" + configuration.getBase64Label() + "</Label>"); if (configuration.getUpgradeRole() != null) { buf.append("<RoleToUpgrade>" + configuration.getUpgradeRole() + "</RoleToUpgrade>"); } buf.append("</UpgradeDeployment>"); request.setHeader(HeaderNames.ContentType, APPLICATION_XML); ((HttpEntityEnclosingRequest) request).setEntity(new ByteArrayEntity(buf.toString().getBytes())); return sendAsynchronousRequest(request, callback); }