Java Code Examples for org.apache.commons.httpclient.HttpMethodBase#addRequestHeader()

The following examples show how to use org.apache.commons.httpclient.HttpMethodBase#addRequestHeader() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: OAuthSampler.java    From jmeter-plugins with Apache License 2.0 6 votes vote down vote up
private void overrideHeaders(HttpMethodBase httpMethod, String url,
                             String method) {
    String headers = getRequestHeaders();
    String[] header = headers.split(System.getProperty("line.separator"));
    for (String kvp : header) {
        int pos = kvp.indexOf(':');
        if (pos < 0) {
            pos = kvp.indexOf('=');
        }
        if (pos > 0) {
            String k = kvp.substring(0, pos).trim();
            String v = "";
            if (kvp.length() > pos + 1) {
                v = kvp.substring(pos + 1).trim();
            }
            httpMethod.addRequestHeader(k, v);
        }
    }
    String authorization = OAuthGenerator.getInstance(getConsumerKey(),
            getConsumerSecret()).getAuthorization(url, method);
    httpMethod.addRequestHeader("Authorization", authorization);
}
 
Example 2
Source File: HMACFilterAuthenticationProvider.java    From Knowage-Server with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 *
 * @param method
 * @throws HMACSecurityException
 */
public void provideAuthentication(HttpMethodBase method, String body) throws HMACSecurityException {

	String token = validator.generateToken();
	Assert.assertNotNull(token, "token");
	String signature;
	try {
		signature = getSignature(method, body, token);
	} catch (Exception e) {
		throw new HMACSecurityException("Problems while signing the request", e);
	}

	method.addRequestHeader(HMACUtils.HMAC_TOKEN_HEADER, token);
	method.addRequestHeader(HMACUtils.HMAC_SIGNATURE_HEADER, signature);
}
 
Example 3
Source File: SwiftRestClient.java    From hadoop with Apache License 2.0 5 votes vote down vote up
/**
 * Add the headers to the method, and the auth token (which must be set
 * @param method method to update
 * @param requestHeaders the list of headers
 * @throws SwiftInternalStateException not yet authenticated
 */
private void setHeaders(HttpMethodBase method, Header[] requestHeaders)
    throws SwiftInternalStateException {
    for (Header header : requestHeaders) {
      method.addRequestHeader(header);
    }
  setAuthToken(method, getToken());
}
 
Example 4
Source File: OldHttpClientApi.java    From javabase with Apache License 2.0 5 votes vote down vote up
private static byte[] executeMethod(HttpMethodBase method, int timeout) throws Exception {
    InputStream in = null;
    try {
        method.addRequestHeader("Connection", "close");
        HttpClient client = new HttpClient();
        HttpConnectionManagerParams params = client.getHttpConnectionManager().getParams();
        //设置连接时候一些参数
        params.setConnectionTimeout(timeout);
        params.setSoTimeout(timeout);
        params.setStaleCheckingEnabled(false);
        ByteArrayOutputStream baos = new ByteArrayOutputStream(BUFFER_SIZE);

        int stat =  client.executeMethod(method);
        if (stat != HttpStatus.SC_OK)
            log.error("get失败!");

        //method.getResponseBody()
        in = method.getResponseBodyAsStream();
        byte[] buffer = new byte[BUFFER_SIZE];
        int len;
        while ((len = in.read(buffer)) > 0) {
            baos.write(buffer, 0, len);
        }
        return baos.toByteArray();
    }
    finally {
        if (in != null) {
            in.close();
        }
    }
}
 
Example 5
Source File: SwiftRestClient.java    From big-c with Apache License 2.0 5 votes vote down vote up
/**
 * Add the headers to the method, and the auth token (which must be set
 * @param method method to update
 * @param requestHeaders the list of headers
 * @throws SwiftInternalStateException not yet authenticated
 */
private void setHeaders(HttpMethodBase method, Header[] requestHeaders)
    throws SwiftInternalStateException {
    for (Header header : requestHeaders) {
      method.addRequestHeader(header);
    }
  setAuthToken(method, getToken());
}
 
Example 6
Source File: SwiftRestClient.java    From sahara-extra with Apache License 2.0 5 votes vote down vote up
/**
 * Add the headers to the method, and the auth token (which must be set
 * @param method method to update
 * @param requestHeaders the list of headers
 * @throws SwiftInternalStateException not yet authenticated
 */
private void setHeaders(HttpMethodBase method, Header[] requestHeaders)
    throws SwiftInternalStateException {
    for (Header header : requestHeaders) {
      method.addRequestHeader(header);
    }
  setAuthToken(method, getToken());
}
 
Example 7
Source File: RestUtilities.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
public static Response makeRequest(HttpMethod httpMethod, String address, Map<String, String> requestHeaders, String requestBody,
		List<NameValuePair> queryParams, boolean authenticate) throws HttpException, IOException, HMACSecurityException {
	logger.debug("httpMethod = " + httpMethod);
	logger.debug("address = " + address);
	logger.debug("requestHeaders = " + requestHeaders);
	logger.debug("requestBody = " + requestBody);

	HttpMethodBase method = getMethod(httpMethod, address);
	if (requestHeaders != null) {
		for (Entry<String, String> entry : requestHeaders.entrySet()) {
			method.addRequestHeader(entry.getKey(), entry.getValue());
		}
	}
	if (queryParams != null) {
		// add uri query params to provided query params present in query
		List<NameValuePair> addressPairs = getAddressPairs(address);
		List<NameValuePair> totalPairs = new ArrayList<NameValuePair>(addressPairs);
		totalPairs.addAll(queryParams);
		method.setQueryString(totalPairs.toArray(new NameValuePair[queryParams.size()]));
	}
	if (method instanceof EntityEnclosingMethod) {
		EntityEnclosingMethod eem = (EntityEnclosingMethod) method;
		// charset of request currently not used
		eem.setRequestBody(requestBody);
	}

	if (authenticate) {
		String hmacKey = SpagoBIUtilities.getHmacKey();
		if (hmacKey != null && !hmacKey.isEmpty()) {
			logger.debug("HMAC key found with value [" + hmacKey + "]. Requests will be authenticated.");
			HMACFilterAuthenticationProvider authenticationProvider = new HMACFilterAuthenticationProvider(hmacKey);
			authenticationProvider.provideAuthentication(method, requestBody);
		} else {
			throw new SpagoBIRuntimeException("The request need to be authenticated, but hmacKey wasn't found.");
		}
	}

	try {
		HttpClient client = getHttpClient(address);
		int statusCode = client.executeMethod(method);
		Header[] headers = method.getResponseHeaders();
		String res = method.getResponseBodyAsString();
		return new Response(res, statusCode, headers);
	} finally {
		method.releaseConnection();
	}
}
 
Example 8
Source File: RestUtilities.java    From Knowage-Server with GNU Affero General Public License v3.0 4 votes vote down vote up
@SuppressWarnings("deprecation")
public static InputStream makeRequestGetStream(HttpMethod httpMethod, String address, Map<String, String> requestHeaders, String requestBody,
		List<NameValuePair> queryParams, boolean authenticate) throws HttpException, IOException, HMACSecurityException {
	final HttpMethodBase method = getMethod(httpMethod, address);
	if (requestHeaders != null) {
		for (Entry<String, String> entry : requestHeaders.entrySet()) {
			method.addRequestHeader(entry.getKey(), entry.getValue());
		}
	}
	if (queryParams != null) {
		// add uri query params to provided query params present in query
		List<NameValuePair> addressPairs = getAddressPairs(address);
		List<NameValuePair> totalPairs = new ArrayList<NameValuePair>(addressPairs);
		totalPairs.addAll(queryParams);
		method.setQueryString(totalPairs.toArray(new NameValuePair[queryParams.size()]));
	}
	if (method instanceof EntityEnclosingMethod) {
		EntityEnclosingMethod eem = (EntityEnclosingMethod) method;
		// charset of request currently not used
		eem.setRequestBody(requestBody);
	}

	if (authenticate) {
		String hmacKey = SpagoBIUtilities.getHmacKey();
		if (hmacKey != null && !hmacKey.isEmpty()) {
			logger.debug("HMAC key found with value [" + hmacKey + "]. Requests will be authenticated.");
			HMACFilterAuthenticationProvider authenticationProvider = new HMACFilterAuthenticationProvider(hmacKey);
			authenticationProvider.provideAuthentication(method, requestBody);
		} else {
			throw new SpagoBIRuntimeException("The request need to be authenticated, but hmacKey wasn't found.");
		}
	}

	HttpClient client = getHttpClient(address);
	int statusCode = client.executeMethod(method);
	logger.debug("Status code " + statusCode);
	Header[] headers = method.getResponseHeaders();
	logger.debug("Response header " + headers);
	Asserts.check(statusCode == HttpStatus.SC_OK, "Response not OK.\nStatus code: " + statusCode);

	return new FilterInputStream(method.getResponseBodyAsStream()) {
		@Override
		public void close() throws IOException {
			try {
				super.close();
			} finally {
				method.releaseConnection();
			}
		}
	};
}
 
Example 9
Source File: KylinClient.java    From Kylin with Apache License 2.0 4 votes vote down vote up
private void addPostHeaders(HttpMethodBase method) {
    method.addRequestHeader("Accept", "application/json, text/plain, */*");
    method.addRequestHeader("Content-Type", "application/json");
    method.addRequestHeader("Authorization", "Basic " + conn.getBasicAuthHeader());
}
 
Example 10
Source File: SwiftRestClient.java    From hadoop with Apache License 2.0 2 votes vote down vote up
/**
 * Set the auth key header of the method to the token ID supplied
 *
 * @param method method
 * @param accessToken access token
 * @throws SwiftInternalStateException if the client is not yet authenticated
 */
private void setAuthToken(HttpMethodBase method, AccessToken accessToken)
    throws SwiftInternalStateException {
  checkNotNull(accessToken,"Not authenticated");
  method.addRequestHeader(HEADER_AUTH_KEY, accessToken.getId());
}
 
Example 11
Source File: SwiftRestClient.java    From big-c with Apache License 2.0 2 votes vote down vote up
/**
 * Set the auth key header of the method to the token ID supplied
 *
 * @param method method
 * @param accessToken access token
 * @throws SwiftInternalStateException if the client is not yet authenticated
 */
private void setAuthToken(HttpMethodBase method, AccessToken accessToken)
    throws SwiftInternalStateException {
  checkNotNull(accessToken,"Not authenticated");
  method.addRequestHeader(HEADER_AUTH_KEY, accessToken.getId());
}