Search in sources :

Example 56 with CloseableHttpClient

use of org.apache.http.impl.client.CloseableHttpClient in project Asqatasun by Asqatasun.

the class HttpRequestHandler method getHttpStatusFromGet.

public int getHttpStatusFromGet(String url) throws IOException {
    String encodedUrl = getEncodedUrl(url);
    CloseableHttpClient httpClient = getHttpClient(encodedUrl);
    HttpGet get = new HttpGet(encodedUrl);
    try {
        LOGGER.debug("executing get request to retrieve status on " + get.getURI());
        HttpResponse status = httpClient.execute(get);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("received " + status + " from get request");
            for (Header h : get.getAllHeaders()) {
                LOGGER.debug("header : " + h.getName() + " " + h.getValue());
            }
        }
        return status.getStatusLine().getStatusCode();
    } catch (UnknownHostException uhe) {
        LOGGER.warn("UnknownHostException on " + encodedUrl);
        return HttpStatus.SC_NOT_FOUND;
    } catch (IOException ioe) {
        LOGGER.warn("IOException on " + encodedUrl);
        return HttpStatus.SC_NOT_FOUND;
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        get.releaseConnection();
        httpClient.close();
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) Header(org.apache.http.Header) UnknownHostException(java.net.UnknownHostException) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException)

Example 57 with CloseableHttpClient

use of org.apache.http.impl.client.CloseableHttpClient in project Asqatasun by Asqatasun.

the class HttpRequestHandler method getHttpContent.

public String getHttpContent(String url) throws URISyntaxException, UnknownHostException, IOException, IllegalCharsetNameException {
    if (StringUtils.isEmpty(url)) {
        return "";
    }
    String encodedUrl = getEncodedUrl(url);
    CloseableHttpClient httpClient = getHttpClient(encodedUrl);
    HttpGet get = new HttpGet(encodedUrl);
    try {
        LOGGER.debug("executing request to retrieve content on " + get.getURI());
        HttpResponse response = httpClient.execute(get);
        LOGGER.debug("received " + response.getStatusLine().getStatusCode() + " from get request");
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            LOGGER.debug("status == HttpStatus.SC_OK ");
            return EntityUtils.toString(response.getEntity(), Charset.defaultCharset());
        } else {
            LOGGER.debug("status != HttpStatus.SC_OK ");
            return "";
        }
    } catch (NullPointerException ioe) {
        LOGGER.debug("NullPointerException");
        return "";
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        get.releaseConnection();
        LOGGER.debug("finally");
        httpClient.close();
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpGet(org.apache.http.client.methods.HttpGet) HttpResponse(org.apache.http.HttpResponse)

Example 58 with CloseableHttpClient

use of org.apache.http.impl.client.CloseableHttpClient in project Asqatasun by Asqatasun.

the class HttpRequestHandler method getHttpStatus.

public int getHttpStatus(String url) throws IOException {
    String encodedUrl = getEncodedUrl(url);
    CloseableHttpClient httpClient = getHttpClient(encodedUrl);
    HttpHead head = new HttpHead(encodedUrl);
    try {
        LOGGER.debug("executing head request to retrieve page status on " + head.getURI());
        HttpResponse response = httpClient.execute(head);
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("received " + response.getStatusLine().getStatusCode() + " from head request");
            for (Header h : head.getAllHeaders()) {
                LOGGER.debug("header : " + h.getName() + " " + h.getValue());
            }
        }
        return response.getStatusLine().getStatusCode();
    } catch (UnknownHostException uhe) {
        LOGGER.warn("UnknownHostException on " + encodedUrl);
        return HttpStatus.SC_NOT_FOUND;
    } catch (IllegalArgumentException iae) {
        LOGGER.warn("IllegalArgumentException on " + encodedUrl);
        return HttpStatus.SC_NOT_FOUND;
    } catch (IOException ioe) {
        LOGGER.warn("IOException on " + encodedUrl);
        return HttpStatus.SC_NOT_FOUND;
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        head.releaseConnection();
        httpClient.close();
    }
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) Header(org.apache.http.Header) UnknownHostException(java.net.UnknownHostException) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) HttpHead(org.apache.http.client.methods.HttpHead)

Example 59 with CloseableHttpClient

use of org.apache.http.impl.client.CloseableHttpClient in project ats-framework by Axway.

the class AtsDbLoggerUtilities method attachFileToCurrentTest.

/**
     * Attach a local file to the current test case in the Test Explorer DB.
     * </br>The file must not be bigger than 10MB
     * 
     * @param fileLocation the absolute path to the file
     * @param testExplorerContextName the name of the web application, e.g. "TestExplorer" or "TestExplorer-3.11.0" etc.
     * @param testExplorerPort the port of the web application, e.g. 8080
     * @return TRUE if the operation was successful and false if not. A warning will be logged on failure.
     */
@PublicAtsApi
public boolean attachFileToCurrentTest(String fileLocation, String testExplorerContextName, int testExplorerPort) {
    ERR_MSG_PREFIX = ERR_MSG_PREFIX.replace("{FILE}", fileLocation);
    if (!checkFileExist(fileLocation)) {
        return false;
    }
    if (!checkFileSizeIsNotTooLarge(fileLocation)) {
        return false;
    }
    ActiveDbAppender dbAppender = ActiveDbAppender.getCurrentInstance();
    if (dbAppender == null) {
        logger.warn(ERR_MSG_PREFIX + "Perhaps the database logging is turned off");
        return false;
    }
    final int runId = dbAppender.getRunId();
    final int suiteId = dbAppender.getSuiteId();
    final int testcaseId = dbAppender.getTestCaseId();
    if (runId < 1 || suiteId < 1 || testcaseId < 1) {
        logger.warn(ERR_MSG_PREFIX + "Perhaps the database logging is turned off or you are trying to log while a testcase is not yet started");
        return false;
    }
    final String database = dbAppender.getDatabase();
    final String host = dbAppender.getHost();
    final String URL = "http://" + host + ":" + testExplorerPort + "/" + testExplorerContextName + "/UploadServlet";
    URL url = null;
    try {
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(URL);
        url = post.getURI().toURL();
        if (!isURLConnetionAvailable(url)) {
            return false;
        }
        logger.debug("POSTing " + fileLocation + " on " + URL);
        File file = new File(fileLocation);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addBinaryBody("upfile", file, ContentType.DEFAULT_BINARY, fileLocation);
        builder.addTextBody("dbName", database);
        builder.addTextBody("runId", Integer.toString(runId));
        builder.addTextBody("suiteId", Integer.toString(suiteId));
        builder.addTextBody("testcaseId", Integer.toString(testcaseId));
        HttpEntity entity = builder.build();
        post.setEntity(entity);
        checkPostExecutedSuccessfully(client.execute(post), fileLocation);
    } catch (FileNotFoundException fnfe) {
        logger.warn(ERR_MSG_PREFIX + "it does not exist on the local file system", fnfe);
        return false;
    } catch (ClientProtocolException cpe) {
        logger.warn(ERR_MSG_PREFIX + "Upload to \"" + url + "\" failed", cpe);
        return false;
    } catch (ConnectException ce) {
        logger.warn(ERR_MSG_PREFIX + "Upload to \"" + url + "\" failed", ce);
        return false;
    } catch (IOException ioe) {
        logger.warn(ERR_MSG_PREFIX + "Upload to \"" + url + "\" failed", ioe);
        return false;
    }
    logger.info("Successfully attached \"" + fileLocation + "\" to the current Test Explorer testcase");
    return true;
}
Also used : CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) HttpPost(org.apache.http.client.methods.HttpPost) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) HttpEntity(org.apache.http.HttpEntity) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException) URL(java.net.URL) ClientProtocolException(org.apache.http.client.ClientProtocolException) ActiveDbAppender(com.axway.ats.log.appenders.ActiveDbAppender) File(java.io.File) ConnectException(java.net.ConnectException) PublicAtsApi(com.axway.ats.common.PublicAtsApi)

Example 60 with CloseableHttpClient

use of org.apache.http.impl.client.CloseableHttpClient in project intellij-community by JetBrains.

the class EduStepicAuthorizedClient method getTokens.

@Nullable
private static StepicWrappers.TokenInfo getTokens(@NotNull final List<NameValuePair> parameters) {
    final Gson gson = new GsonBuilder().setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES).create();
    final HttpPost request = new HttpPost(EduStepicNames.TOKEN_URL);
    request.setEntity(new UrlEncodedFormEntity(parameters, Consts.UTF_8));
    try {
        final CloseableHttpClient client = EduStepicClient.getHttpClient();
        final CloseableHttpResponse response = client.execute(request);
        final StatusLine statusLine = response.getStatusLine();
        final HttpEntity responseEntity = response.getEntity();
        final String responseString = responseEntity != null ? EntityUtils.toString(responseEntity) : "";
        EntityUtils.consume(responseEntity);
        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
            return gson.fromJson(responseString, StepicWrappers.TokenInfo.class);
        } else {
            LOG.warn("Failed to Login: " + statusLine.getStatusCode() + statusLine.getReasonPhrase());
        }
    } catch (IOException e) {
        LOG.warn(e.getMessage());
    }
    return null;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) GsonBuilder(com.google.gson.GsonBuilder) CloseableHttpResponse(org.apache.http.client.methods.CloseableHttpResponse) Gson(com.google.gson.Gson) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) IOException(java.io.IOException) Nullable(org.jetbrains.annotations.Nullable)

Aggregations

CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)430 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)238 HttpGet (org.apache.http.client.methods.HttpGet)212 Test (org.junit.Test)206 HttpResponse (org.apache.http.HttpResponse)108 HttpEntity (org.apache.http.HttpEntity)92 IOException (java.io.IOException)90 HttpPost (org.apache.http.client.methods.HttpPost)85 StringEntity (org.apache.http.entity.StringEntity)67 InputStream (java.io.InputStream)57 StatusLine (org.apache.http.StatusLine)41 HttpHost (org.apache.http.HttpHost)36 URI (java.net.URI)35 RequestConfig (org.apache.http.client.config.RequestConfig)32 Header (org.apache.http.Header)24 HttpClientContext (org.apache.http.client.protocol.HttpClientContext)24 File (java.io.File)22 HttpPut (org.apache.http.client.methods.HttpPut)22 BasicCredentialsProvider (org.apache.http.impl.client.BasicCredentialsProvider)20 ByteArrayInputStream (java.io.ByteArrayInputStream)19