Package org.apache.http.client.methods

Examples of org.apache.http.client.methods.HttpRequestBase


        HTTPSampleResult res = createSampleResult(url, method);

        HttpClient httpClient = setupClient(url);
       
        HttpRequestBase httpRequest = null;
        try {
            URI uri = url.toURI();
            if (method.equals(HTTPConstants.POST)) {
                httpRequest = new HttpPost(uri);
            } else if (method.equals(HTTPConstants.PUT)) {
                httpRequest = new HttpPut(uri);
            } else if (method.equals(HTTPConstants.HEAD)) {
                httpRequest = new HttpHead(uri);
            } else if (method.equals(HTTPConstants.TRACE)) {
                httpRequest = new HttpTrace(uri);
            } else if (method.equals(HTTPConstants.OPTIONS)) {
                httpRequest = new HttpOptions(uri);
            } else if (method.equals(HTTPConstants.DELETE)) {
                httpRequest = new HttpDelete(uri);
            } else if (method.equals(HTTPConstants.GET)) {
                httpRequest = new HttpGet(uri);
            } else if (method.equals(HTTPConstants.PATCH)) {
                httpRequest = new HttpPatch(uri);
            } else {
                throw new IllegalArgumentException("Unexpected method: '"+method+"'");
            }
            setupRequest(url, httpRequest, res); // can throw IOException
        } catch (Exception e) {
            res.sampleStart();
            res.sampleEnd();
            errorResult(e, res);
            return res;
        }

        HttpContext localContext = new BasicHttpContext();
       
        res.sampleStart();

        final CacheManager cacheManager = getCacheManager();
        if (cacheManager != null && HTTPConstants.GET.equalsIgnoreCase(method)) {
           if (cacheManager.inCache(url)) {
               res.sampleEnd();
               res.setResponseNoContent();
               res.setSuccessful(true);
               return res;
           }
        }

        try {
            currentRequest = httpRequest;
            handleMethod(method, res, httpRequest, localContext);
            // perform the sample
            HttpResponse httpResponse =
                    executeRequest(httpClient, httpRequest, localContext, url);

            // Needs to be done after execute to pick up all the headers
            final HttpRequest request = (HttpRequest) localContext.getAttribute(ExecutionContext.HTTP_REQUEST);
            // We've finished with the request, so we can add the LocalAddress to it for display
            final InetAddress localAddr = (InetAddress) httpRequest.getParams().getParameter(ConnRoutePNames.LOCAL_ADDRESS);
            if (localAddr != null) {
                request.addHeader(HEADER_LOCAL_ADDRESS, localAddr.toString());
            }
            res.setRequestHeaders(getConnectionHeaders(request));

            Header contentType = httpResponse.getLastHeader(HTTPConstants.HEADER_CONTENT_TYPE);
            if (contentType != null){
                String ct = contentType.getValue();
                res.setContentType(ct);
                res.setEncodingAndType(ct);                   
            }
            HttpEntity entity = httpResponse.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                res.setResponseData(readResponse(res, instream, (int) entity.getContentLength()));
            }
           
            res.sampleEnd(); // Done with the sampling proper.
            currentRequest = null;

            // Now collect the results into the HTTPSampleResult:
            StatusLine statusLine = httpResponse.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            res.setResponseCode(Integer.toString(statusCode));
            res.setResponseMessage(statusLine.getReasonPhrase());
            res.setSuccessful(isSuccessCode(statusCode));

            res.setResponseHeaders(getResponseHeaders(httpResponse));
            if (res.isRedirect()) {
                final Header headerLocation = httpResponse.getLastHeader(HTTPConstants.HEADER_LOCATION);
                if (headerLocation == null) { // HTTP protocol violation, but avoids NPE
                    throw new IllegalArgumentException("Missing location header in redirect for " + httpRequest.getRequestLine());
                }
                String redirectLocation = headerLocation.getValue();
                if(!STRICT_RFC_2616 && !(redirectLocation.startsWith("http://")|| redirectLocation.startsWith("https://"))) {
                    redirectLocation = ConversionUtils.buildFullUrlFromRelative(url, redirectLocation);
                }
                try {
                    final URL redirectUrl = new URL(redirectLocation);
                    res.setRedirectLocation(ConversionUtils.sanitizeUrl(redirectUrl).toString());
                } catch (Exception e) {
                    log.error("Error in redirect URL for "  + httpRequest.getRequestLine()
                            +"\n\tCould not sanitize URL: " + redirectLocation + "\n\t", e);
                }
            }

            // record some sizes to allow HTTPSampleResult.getBytes() with different options
View Full Code Here


            client.getCredentialsProvider().setCredentials(
                new AuthScope(componentConfig.getEndPointUrl().getHost(), componentConfig.getEndPointUrl().getPort(),
                    realm), new UsernamePasswordCredentials(userName, password));
        }

        HttpRequestBase method;
        switch (componentConfig.getHttpMethod()) {
        case GET:
            method = new HttpGet(componentConfig.getEndPointUrl().toExternalForm());
            break;
        case HEAD:
            method = new HttpHead(componentConfig.getEndPointUrl().toExternalForm());
            break;
        default:
            throw new RuntimeException("Unsupported http method: '" + componentConfig.getHttpMethod() + "'");
        }
        Boolean followRedirects = pluginConfig.getSimple(ConfigKeys.FOLOW_REDIRECTS).getBooleanValue();
        HttpParams httpParams = client.getParams();
        HttpClientParams.setRedirecting(httpParams, followRedirects == null ? false : followRedirects.booleanValue());

        switch (componentConfig.getProxyMode()) {
        case MANUAL:
            HttpHost proxy = new HttpHost(componentConfig.getProxyHost(), componentConfig.getProxyPort());
            httpParams.setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
            break;
        case SYS_PROPS:
            ProxySelectorRoutePlanner routePlanner = new ProxySelectorRoutePlanner(client.getConnectionManager()
                .getSchemeRegistry(), ProxySelector.getDefault());
            client.setRoutePlanner(routePlanner);
            break;
        default:
        }

        try {

            long start = System.nanoTime();
            HttpResponse response = client.execute(method);
            long connectTime = NANOSECONDS.toMillis(System.nanoTime() - start);

            // Availability may depend on reponse code value
            int responseCode = response.getStatusLine().getStatusCode();
            boolean success = !pluginConfig.getSimple(ConfigKeys.VALIDATE_RESPONSE_CODE).getBooleanValue()
                || (responseCode >= 200 && responseCode <= 299);
            // Availability may depend on reponse content matching a pattern
            success = success
                && (componentConfig.getResponseValidationPattern() == null || componentConfig
                    .getResponseValidationPattern().matcher(getResponseBody(response)).find());

            long readTime = NANOSECONDS.toMillis(System.nanoTime() - start);

            Header dateHeader = response.getFirstHeader("Date");
            Date contentDate = dateHeader == null ? null : DateUtils.parseDate(dateHeader.getValue());
            HttpEntity entity = response.getEntity();

            if (metrics != null) {
                for (MeasurementScheduleRequest request : metrics) {
                    if (request.getName().equals("connectTime")) {
                        report.addData(new MeasurementDataNumeric(request, (double) connectTime));
                    } else if (request.getName().equals("readTime")) {
                        report.addData(new MeasurementDataNumeric(request, (double) readTime));
                    } else if (request.getName().equals("contentLength")) {
                        if (entity != null) {
                            report.addData(new MeasurementDataNumeric(request, (double) entity.getContentLength()));
                        }
                    } else if (request.getName().equals("contentAge")) {
                        if (contentDate != null) {
                            report.addData(new MeasurementDataNumeric(request,
                                (double) (System.currentTimeMillis() - contentDate.getTime())));
                        }
                    }
                }
            }

            return success;

        } catch (Exception e) {
            if (LOG.isTraceEnabled()) {
                LOG.trace(e);
            }
        } finally {
            method.abort();
            client.getConnectionManager().shutdown();
        }
        return false;
    }
View Full Code Here

    }

    APILoginResult result = new APILoginResult();
       
    try {
      HttpRequestBase method = getInitializedPostMethod(loginURL,loginParams);
      ExecuteAPILoginThread t = new ExecuteAPILoginThread(client, method, result);
      try {
        t.start();
        t.join();

        handleException(t.getException());
      } catch (ManifoldCFException e) {
        t.interrupt();
        throw e;
      } catch (ServiceInterruption e) {
        t.interrupt();
        throw e;
      } catch (IOException e) {
        t.interrupt();
        throw e;
      } catch (HttpException e) {
  t.interrupt();
  throw e;
      } catch (InterruptedException e) {
        t.interrupt();
        // We need the caller to abandon any connections left around, so rethrow in a way that forces them to process the event properly.
        throw e;
      }
     
      if (result.result)
        return true;
     
      // Grab the token from the first call
      token = t.getToken();
      if (token == null)
      {
        // We don't need a token, we just couldn't log in
        Logging.connectors.debug("WIKI API login error: '" + result.reason + "'");
        throw new ManifoldCFException("WIKI API login error: " + result.reason, null, ManifoldCFException.REPOSITORY_CONNECTION_ERROR);
      }
     
    } catch (InterruptedException e) {
      throw new ManifoldCFException("Interrupted: " + e.getMessage(), e, ManifoldCFException.INTERRUPTED);
    } catch (ManifoldCFException e) {
      throw e;
    } catch (java.net.SocketTimeoutException e) {
      long currentTime = System.currentTimeMillis();
      throw new ServiceInterruption("Login timed out reading from the Wiki server: " + e.getMessage(), e, currentTime + 300000L, currentTime + 12L * 60000L, -1, false);
    } catch (java.net.SocketException e) {
      long currentTime = System.currentTimeMillis();
      throw new ServiceInterruption("Login received a socket error reading from Wiki server: " + e.getMessage(), e, currentTime + 300000L, currentTime + 12L * 60000L, -1, false);
    } catch (ConnectTimeoutException e) {
      long currentTime = System.currentTimeMillis();
      throw new ServiceInterruption("Login connection timed out reading from Wiki server: " + e.getMessage(), e, currentTime + 300000L, currentTime + 12L * 60000L, -1, false);
    } catch (InterruptedIOException e) {
      throw new ManifoldCFException("Interrupted: " + e.getMessage(), e, ManifoldCFException.INTERRUPTED);
    } catch (IOException e) {
      throw new ManifoldCFException("Login had an IO failure: " + e.getMessage(), e);
    } catch (HttpException e) {
      throw new ManifoldCFException("Login had an Http exception: "+e.getMessage(), e);
    }

    // First request is finished.  Fire off the second one.
   
    loginParams.put("lgtoken", token);
   
    try {
      HttpRequestBase method = getInitializedPostMethod(loginURL,loginParams);
      ExecuteTokenAPILoginThread t = new ExecuteTokenAPILoginThread(httpClient, method, result);
      try {
        t.start();
        t.join();

View Full Code Here

    while (true)
    {
      HttpClient client = httpClient;
      try
      {
  HttpRequestBase executeMethod = getInitializedGetMethod(getCheckURL());
        ExecuteCheckThread t = new ExecuteCheckThread(client,executeMethod);
        try
        {
          t.start();
          t.join();
View Full Code Here

    boolean loginAttempted = false;
    while (true)
    {
      try
      {
  HttpRequestBase executeMethod = getInitializedGetMethod(getListPagesURL(startPageTitle,namespace,prefix));
        XThreadStringBuffer pageBuffer = new XThreadStringBuffer();
        ExecuteListPagesThread t = new ExecuteListPagesThread(httpClient,executeMethod,pageBuffer,startPageTitle);
        try
        {
          t.start();
View Full Code Here

    boolean loginAttempted = false;
    while (true)
    {
      try
      {
  HttpRequestBase executeMethod = getInitializedGetMethod(getGetDocURLsURL(documentIdentifiers));
        ExecuteGetDocURLsThread t = new ExecuteGetDocURLsThread(httpClient,executeMethod,urls);
        try
        {
          t.start();
          t.join();
View Full Code Here

    boolean loginAttempted = false;
    while (true)
    {
      try
      {
  HttpRequestBase executeMethod = getInitializedGetMethod(getGetTimestampURL(documentIdentifiers));
        ExecuteGetTimestampThread t = new ExecuteGetTimestampThread(httpClient,executeMethod,versions);
        try
        {
          t.start();
          t.join();
View Full Code Here

    boolean loginAttempted = false;
    while (true)
    {
      try
      {
  HttpRequestBase executeMethod = getInitializedGetMethod(getGetNamespacesURL());
        ExecuteGetNamespacesThread t = new ExecuteGetNamespacesThread(httpClient,executeMethod,namespaces);
        try
        {
          t.start();
          t.join();
View Full Code Here

      long startTime = System.currentTimeMillis();
      long dataSize = 0L;
     
      try
      {
  HttpRequestBase executeMethod = getInitializedGetMethod(getGetDocInfoURL(documentIdentifier));
        ExecuteGetDocInfoThread t = new ExecuteGetDocInfoThread(httpClient,executeMethod,documentIdentifier);
        try
        {
          t.start();
          t.join();
View Full Code Here

            os = adaptOutputStream(ncos, request, context.getOutputStreamAdapters());
            // prepare the entity that will write our entity
            entityWriter = new EntityWriter(this, request, os, ncos);
        }

        HttpRequestBase entityRequest = setupHttpRequest(request, client, entityWriter);

        return client.execute(entityRequest);
    }
View Full Code Here

TOP

Related Classes of org.apache.http.client.methods.HttpRequestBase

Copyright © 2018 www.massapicom. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.