Java Code Examples for org.apache.commons.httpclient.HttpMethod#setRequestHeader()

The following examples show how to use org.apache.commons.httpclient.HttpMethod#setRequestHeader() . 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: GrafanaDashboardServiceImpl.java    From cymbal with Apache License 2.0 6 votes vote down vote up
private void doHttpAPI(HttpMethod method) throws MonitorException {
    // 拼装http post请求,调用grafana http api建立dashboard
    HttpClient httpclient = new HttpClient();
    httpclient.getParams().setConnectionManagerTimeout(Constant.Http.CONN_TIMEOUT);
    httpclient.getParams().setSoTimeout(Constant.Http.SO_TIMEOUT);

    // api key
    method.setRequestHeader("Authorization", String.format("Bearer %s", grafanaApiKey));
    try {

        int statusCode = httpclient.executeMethod(method);
        // 若http请求失败
        if (statusCode != Constant.Http.STATUS_OK) {
            String responseBody = method.getResponseBodyAsString();
            throw new MonitorException(responseBody);
        }
    } catch (Exception e) {
        if (e instanceof MonitorException) {
            throw (MonitorException) e;
        } else {
            new MonitorException(e);
        }
    } finally {
        method.releaseConnection();
    }
}
 
Example 2
Source File: HttpClientConnection.java    From knopflerfish.org with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public void setRequestProperty(String key, String value) throws IOException {

    if (state == STATE_CLOSED) {
      init();
    }

    if (state != STATE_SETUP) {
      throw new IllegalStateException("Already connected");
    }

    if (out != null && !(HttpConnection.POST.equals(method) || PUT_METHOD.equals(method))) {
      // When an outputstream has been created these calls are ignored.
      return ;
    }

    HttpMethod res = getResult();
    res.setRequestHeader(key, value);
  }
 
Example 3
Source File: HttpMethodClientHeaderAdaptor.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Override
public void setHeader(HttpMethod httpMethod, String name, String value) {
    httpMethod.setRequestHeader(name, value);
    if (isDebug) {
        logger.debug("Set header {}={}", name, value);
    }
}
 
Example 4
Source File: JobEndNotifier.java    From hadoop-gpu with Apache License 2.0 5 votes vote down vote up
private static int httpNotification(String uri) throws IOException {
  URI url = new URI(uri, false);
  HttpClient m_client = new HttpClient();
  HttpMethod method = new GetMethod(url.getEscapedURI());
  method.setRequestHeader("Accept", "*/*");
  return m_client.executeMethod(method);
}
 
Example 5
Source File: WebdavFileObject.java    From commons-vfs with Apache License 2.0 5 votes vote down vote up
/**
 * Prepares a Method object.
 *
 * @param method the HttpMethod.
 * @throws FileSystemException if an error occurs encoding the uri.
 * @throws URIException if the URI is in error.
 */
@Override
protected void setupMethod(final HttpMethod method) throws FileSystemException, URIException {
    final String pathEncoded = ((URLFileName) getName()).getPathQueryEncoded(this.getUrlCharset());
    method.setPath(pathEncoded);
    method.setFollowRedirects(this.getFollowRedirect());
    method.setRequestHeader("User-Agent", "Jakarta-Commons-VFS");
    method.addRequestHeader("Cache-control", "no-cache");
    method.addRequestHeader("Cache-store", "no-store");
    method.addRequestHeader("Pragma", "no-cache");
    method.addRequestHeader("Expires", "0");
}
 
Example 6
Source File: HeaderProcessor.java    From elasticsearch-hadoop with Apache License 2.0 5 votes vote down vote up
public HttpMethod applyTo(HttpMethod method) {
    // Add headers to the request.
    for (Header header : headers) {
        method.setRequestHeader(header);
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Added HTTP Headers to method: " + Arrays.toString(method.getRequestHeaders()));
    }

    return method;
}
 
Example 7
Source File: TraceeHttpClientDecorator.java    From tracee with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
private void preRequest(HttpMethod httpMethod) {
	final TraceeFilterConfiguration filterConfiguration = backend.getConfiguration(profile);
	if (!backend.isEmpty() && filterConfiguration.shouldProcessContext(OutgoingRequest)) {
		final Map<String, String> filteredParams = filterConfiguration.filterDeniedParams(backend.copyToMap(), OutgoingRequest);
		httpMethod.setRequestHeader(TraceeConstants.TPIC_HEADER, transportSerialization.render(filteredParams));
	}
}
 
Example 8
Source File: JobEndNotifier.java    From RDFS with Apache License 2.0 5 votes vote down vote up
private static int httpNotification(String uri) throws IOException {
  URI url = new URI(uri, false);
  HttpClient m_client = new HttpClient();
  HttpMethod method = new GetMethod(url.getEscapedURI());
  method.setRequestHeader("Accept", "*/*");
  return m_client.executeMethod(method);
}
 
Example 9
Source File: HttpUtils.java    From Java-sdk with Apache License 2.0 5 votes vote down vote up
/**
 * 设置请求头部信息
 * @param method
 * @param headers
 */
private static void setHeaders(HttpMethod method,Map<String, String> headers) {
	Set<String> headersKeys = headers.keySet();
	Iterator<String> iterHeaders = headersKeys.iterator();
	while(iterHeaders.hasNext()){
		String key = iterHeaders.next();
		method.setRequestHeader(key, headers.get(key));
	}
}
 
Example 10
Source File: RequestHandlerBase.java    From development with Apache License 2.0 5 votes vote down vote up
/**
 * Will write the proxy specific headers such as Via and x-forwarded-for.
 * 
 * @param method Method to write the headers to
 * @param request The incoming request, will need to get virtual host.
 * @throws HttpException 
 */
private void setProxySpecificHeaders(HttpMethod method, HttpServletRequest request) throws HttpException {
    String serverHostName = "jEasyExtensibleProxy";
    try {
        serverHostName = InetAddress.getLocalHost().getHostName();   
    } catch (UnknownHostException e) {
        log.error("Couldn't get the hostname needed for headers x-forwarded-server and Via", e);
    }
    
    String originalVia = request.getHeader("via");
    StringBuffer via = new StringBuffer("");
    if (originalVia != null) {
        if (originalVia.indexOf(serverHostName) != -1) {
            log.error("This proxy has already handled the request, will abort.");
            throw new HttpException("Request has a cyclic dependency on this proxy.");
        }
        via.append(originalVia).append(", ");
    }
    via.append(request.getProtocol()).append(" ").append(serverHostName);
     
    method.setRequestHeader("via", via.toString());
    method.setRequestHeader("x-forwarded-for", request.getRemoteAddr());     
    method.setRequestHeader("x-forwarded-host", request.getServerName());
    method.setRequestHeader("x-forwarded-server", serverHostName);
    
    method.setRequestHeader("accept-encoding", "");
}
 
Example 11
Source File: DefaultEncryptionUtils.java    From alfresco-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public void setRequestAlgorithmParameters(HttpMethod method, AlgorithmParameters params) throws IOException
{
    if(params != null)
    {
        method.setRequestHeader(HEADER_ALGORITHM_PARAMETERS, Base64.encodeBytes(params.getEncoded()));
    }
}
 
Example 12
Source File: DefaultEncryptionUtils.java    From alfresco-core with GNU Lesser General Public License v3.0 5 votes vote down vote up
protected void setRequestMac(HttpMethod method, byte[] mac)
{
    if(mac == null)
    {
        throw new AlfrescoRuntimeException("Mac cannot be null");
    }
    method.setRequestHeader(HEADER_MAC, Base64.encodeBytes(mac));    
}
 
Example 13
Source File: ApacheHttpClient3IT.java    From uavstack with Apache License 2.0 4 votes vote down vote up
/**
 * for http client
 * 
 * @param args
 * @return
 */
@SuppressWarnings({ "unused", "unchecked" })
public void doStart(Object[] args) {

    HostConfiguration hostconfig = (HostConfiguration) args[0];
    HttpMethod method = (HttpMethod) args[1];
    HttpState state = (HttpState) args[2];

    String httpAction = "";
    method.setRequestHeader("UAV-Client-Src", MonitorServerUtil.getUAVClientSrc(this.applicationId));

    try {
        httpAction = method.getName();
        targetURL = method.getURI().toString();

        // HttpMethod中可能不包含ip:port,需要从httpHost中拿到再拼接
        if (!targetURL.startsWith("http")) {
            targetURL = hostconfig.getHostURL() + targetURL;
        }
    }
    catch (URIException e) {
        // ignore
    }

    Map<String, Object> params = new HashMap<String, Object>();

    params.put(CaptureConstants.INFO_CLIENT_REQUEST_URL, targetURL);
    params.put(CaptureConstants.INFO_CLIENT_REQUEST_ACTION, httpAction);
    params.put(CaptureConstants.INFO_CLIENT_APPID, this.applicationId);
    params.put(CaptureConstants.INFO_CLIENT_TYPE, "apache.http.Client");

    if (logger.isDebugable()) {
        logger.debug("Invoke START:" + targetURL + "," + httpAction + "," + this.applicationId, null);
    }

    UAVServer.instance().runMonitorCaptureOnServerCapPoint(CaptureConstants.CAPPOINT_APP_CLIENT,
            Monitor.CapturePhase.PRECAP, params);

    // register adapter
    UAVServer.instance().runSupporter("com.creditease.uav.apm.supporters.InvokeChainSupporter", "registerAdapter",
            ApacheHttpClient3Adapter.class);

    ivcContextParams = (Map<String, Object>) UAVServer.instance().runSupporter(
            "com.creditease.uav.apm.supporters.InvokeChainSupporter", "runCap",
            InvokeChainConstants.CHAIN_APP_CLIENT, InvokeChainConstants.CapturePhase.PRECAP, params,
            ApacheHttpClient3Adapter.class, args);

}
 
Example 14
Source File: ChatterTools.java    From JavaChatterRESTApi with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
public HttpMethod addHeaders(HttpMethod method, ChatterAuthToken token) {
    method.setRequestHeader("Authorization", "OAuth " + token.getAccessToken());
    method.addRequestHeader("X-PrettyPrint", "1");

    return method;
}
 
Example 15
Source File: AbstractHttpClient.java    From alfresco-core with GNU Lesser General Public License v3.0 4 votes vote down vote up
protected HttpMethod createMethod(Request req) throws IOException
{
    StringBuilder url = new StringBuilder(128);
    url.append(baseUrl);
    url.append("/service/");
    url.append(req.getFullUri());

    // construct method
    HttpMethod httpMethod = null;
    String method = req.getMethod();
    if(method.equalsIgnoreCase("GET"))
    {
        GetMethod get = new GetMethod(url.toString());
        httpMethod = get;
        httpMethod.setFollowRedirects(true);
    }
    else if(method.equalsIgnoreCase("POST"))
    {
        PostMethod post = new PostMethod(url.toString());
        httpMethod = post;
        ByteArrayRequestEntity requestEntity = new ByteArrayRequestEntity(req.getBody(), req.getType());
        if (req.getBody().length > DEFAULT_SAVEPOST_BUFFER)
        {
            post.getParams().setBooleanParameter(HttpMethodParams.USE_EXPECT_CONTINUE, true);
        }
        post.setRequestEntity(requestEntity);
        // Note: not able to automatically follow redirects for POST, this is handled by sendRemoteRequest
    }
    else if(method.equalsIgnoreCase("HEAD"))
    {
        HeadMethod head = new HeadMethod(url.toString());
        httpMethod = head;
        httpMethod.setFollowRedirects(true);
    }
    else
    {
        throw new AlfrescoRuntimeException("Http Method " + method + " not supported");
    }

    if (req.getHeaders() != null)
    {
        for (Map.Entry<String, String> header : req.getHeaders().entrySet())
        {
            httpMethod.setRequestHeader(header.getKey(), header.getValue());
        }
    }
    
    return httpMethod;
}
 
Example 16
Source File: HttpRecorderMethod.java    From webarchive-commons with Apache License 2.0 3 votes vote down vote up
/**
 * If a 'Proxy-Connection' header has been added to the request,
 * it'll be of a 'keep-alive' type.  Until we support 'keep-alives',
 * override the Proxy-Connection setting and instead pass a 'close'
 * (Otherwise every request has to timeout before we notice
 * end-of-document).
 * @param method Method to find proxy-connection header in.
 */
public void handleAddProxyConnectionHeader(HttpMethod method) {
    Header h = method.getRequestHeader("Proxy-Connection");
    if (h != null) {
        h.setValue("close");
        method.setRequestHeader(h);
    }
}
 
Example 17
Source File: HttpFileObject.java    From commons-vfs with Apache License 2.0 3 votes vote down vote up
/**
 * Prepares a HttpMethod object.
 *
 * @param method The object which gets prepared to access the file object.
 * @throws FileSystemException if an error occurs.
 * @throws URIException if path cannot be represented.
 * @since 2.0 (was package)
 */
protected void setupMethod(final HttpMethod method) throws FileSystemException, URIException {
    final String pathEncoded = ((URLFileName) getName()).getPathQueryEncoded(this.getUrlCharset());
    method.setPath(pathEncoded);
    method.setFollowRedirects(this.getFollowRedirect());
    method.setRequestHeader("User-Agent", this.getUserAgent());
}
 
Example 18
Source File: DefaultEncryptionUtils.java    From alfresco-core with GNU Lesser General Public License v3.0 2 votes vote down vote up
/**
 * Set the timestamp on the HTTP request
 * @param method HttpMethod
 * @param timestamp (ms, in UNIX time)
 */
protected void setRequestTimestamp(HttpMethod method, long timestamp)
{
    method.setRequestHeader(HEADER_TIMESTAMP, String.valueOf(timestamp));        
}
 
Example 19
Source File: SwiftRestClient.java    From sahara-extra 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(HttpMethod method, AccessToken accessToken)
    throws SwiftInternalStateException {
  checkNotNull(accessToken,"Not authenticated");
  method.setRequestHeader(HEADER_AUTH_KEY, accessToken.getId());
}