Search in sources :

Example 76 with ClientProtocolException

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

the class HttpClient method performDownloadFile.

@Override
protected void performDownloadFile(String localFile, String remoteDir, String remoteFile) throws FileTransferException {
    checkClientInitialized();
    final String getUrl = constructDownloadUrl(remoteDir, remoteFile);
    log.info("Downloading " + getUrl);
    HttpGet httpGetMethod = new HttpGet(getUrl);
    HttpEntity responseEntity = null;
    OutputStream outstream = null;
    boolean errorSavingFile = true;
    try {
        // add headers specified by the user
        addRequestHeaders(httpGetMethod);
        // download the file
        HttpResponse response = httpClient.execute(httpGetMethod, httpContext);
        if (200 != response.getStatusLine().getStatusCode()) {
            throw new FileTransferException("Downloading " + getUrl + " returned " + response.getStatusLine());
        }
        // save the file
        responseEntity = response.getEntity();
        if (responseEntity != null) {
            outstream = new FileOutputStream(localFile);
            responseEntity.writeTo(outstream);
            outstream.flush();
            errorSavingFile = false;
        } else {
            throw new FileTransferException("No file present in the response");
        }
    } catch (ClientProtocolException e) {
        log.error("Unable to download file!", e);
        throw new FileTransferException(e);
    } catch (IOException e) {
        log.error("Unable to download file!", e);
        throw new FileTransferException(e);
    } finally {
        if (responseEntity != null) {
            IoUtils.closeStream(outstream);
            if (errorSavingFile) {
                try {
                    // We were not able to properly stream the entity content
                    // to the local file system. The next line consumes the
                    // entity content closes the underlying stream.
                    EntityUtils.consume(responseEntity);
                } catch (IOException e) {
                // we tried our best to release the resources
                }
            }
        }
    }
    log.info("Successfully downloaded '" + localFile + "' from '" + remoteDir + remoteFile + "' at " + this.hostname);
}
Also used : FileTransferException(com.axway.ats.common.filetransfer.FileTransferException) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) ByteArrayOutputStream(java.io.ByteArrayOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) FileOutputStream(java.io.FileOutputStream) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException)

Example 77 with ClientProtocolException

use of org.apache.http.client.ClientProtocolException in project Arduino by Wzorek.

the class HomeActivity method sendRequest.

/**
     * Description: Send an HTTP Get request to a specified ip address and port.
     * Also send a parameter "parameterName" with the value of "parameterValue".
     * @param parameterValue the pin number to toggle
     * @param ipAddress the ip address to send the request to
     * @param portNumber the port number of the ip address
     * @param parameterName
     * @return The ip address' reply text, or an ERROR message is it fails to receive one
     */
public String sendRequest(String parameterValue, String ipAddress, String portNumber, String parameterName) {
    String serverResponse = "ERROR";
    try {
        // create an HTTP client
        HttpClient httpclient = new DefaultHttpClient();
        // define the URL e.g. http://myIpaddress:myport/?pin=13 (to toggle pin 13 for example)
        URI website = new URI("http://" + ipAddress + ":" + portNumber + "/?" + parameterName + "=" + parameterValue);
        // create an HTTP GET object
        HttpGet getRequest = new HttpGet();
        // set the URL of the GET request
        getRequest.setURI(website);
        // execute the request
        HttpResponse response = httpclient.execute(getRequest);
        // get the ip address server's reply
        InputStream content = null;
        content = response.getEntity().getContent();
        BufferedReader in = new BufferedReader(new InputStreamReader(content));
        serverResponse = in.readLine();
        // Close the connection
        content.close();
    } catch (ClientProtocolException e) {
        // HTTP error
        serverResponse = e.getMessage();
        e.printStackTrace();
    } catch (IOException e) {
        // IO error
        serverResponse = e.getMessage();
        e.printStackTrace();
    } catch (URISyntaxException e) {
        // URL syntax error
        serverResponse = e.getMessage();
        e.printStackTrace();
    }
    // return the server's reply/response text
    return serverResponse;
}
Also used : InputStreamReader(java.io.InputStreamReader) InputStream(java.io.InputStream) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) HttpGet(org.apache.http.client.methods.HttpGet) BufferedReader(java.io.BufferedReader) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) URISyntaxException(java.net.URISyntaxException) URI(java.net.URI) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ClientProtocolException(org.apache.http.client.ClientProtocolException)

Example 78 with ClientProtocolException

use of org.apache.http.client.ClientProtocolException in project cloudstack by apache.

the class SspClient method executeMethod.

private String executeMethod(HttpRequestBase req, String path) {
    try {
        URI base = new URI(apiUrl);
        req.setURI(new URI(base.getScheme(), base.getUserInfo(), base.getHost(), base.getPort(), path, null, null));
    } catch (URISyntaxException e) {
        s_logger.error("invalid API URL " + apiUrl + " path " + path, e);
        return null;
    }
    try {
        String content = null;
        try {
            content = getHttpClient().execute(req, new BasicResponseHandler());
            s_logger.info("ssp api call: " + req);
        } catch (HttpResponseException e) {
            s_logger.info("ssp api call failed: " + req, e);
            if (e.getStatusCode() == HttpStatus.SC_UNAUTHORIZED && login()) {
                req.reset();
                content = getHttpClient().execute(req, new BasicResponseHandler());
                s_logger.info("ssp api retry call: " + req);
            }
        }
        return content;
    } catch (ClientProtocolException e) {
        // includes HttpResponseException
        s_logger.error("ssp api call failed: " + req, e);
    } catch (IOException e) {
        s_logger.error("ssp api call failed: " + req, e);
    }
    return null;
}
Also used : BasicResponseHandler(org.apache.http.impl.client.BasicResponseHandler) HttpResponseException(org.apache.http.client.HttpResponseException) URISyntaxException(java.net.URISyntaxException) IOException(java.io.IOException) URI(java.net.URI) ClientProtocolException(org.apache.http.client.ClientProtocolException)

Example 79 with ClientProtocolException

use of org.apache.http.client.ClientProtocolException in project cloudstack by apache.

the class TestHttp method testHttpclient.

@Test
@Parameters("template-url")
public void testHttpclient(String templateUrl) {
    final HttpHead method = new HttpHead(templateUrl);
    final DefaultHttpClient client = new DefaultHttpClient();
    OutputStream output = null;
    long length = 0;
    try {
        HttpResponse response = client.execute(method);
        length = Long.parseLong(response.getFirstHeader("Content-Length").getValue());
        System.out.println(response.getFirstHeader("Content-Length").getValue());
        final File localFile = new File("/tmp/test");
        if (!localFile.exists()) {
            localFile.createNewFile();
        }
        final HttpGet getMethod = new HttpGet(templateUrl);
        response = client.execute(getMethod);
        final HttpEntity entity = response.getEntity();
        output = new BufferedOutputStream(new FileOutputStream(localFile));
        entity.writeTo(output);
    } catch (final ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (final IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } finally {
        try {
            if (output != null) {
                output.close();
            }
        } catch (final IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    final File f = new File("/tmp/test");
    Assert.assertEquals(f.length(), length);
}
Also used : HttpEntity(org.apache.http.HttpEntity) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) HttpGet(org.apache.http.client.methods.HttpGet) FileOutputStream(java.io.FileOutputStream) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream) HttpHead(org.apache.http.client.methods.HttpHead) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ClientProtocolException(org.apache.http.client.ClientProtocolException) Parameters(org.testng.annotations.Parameters) Test(org.junit.Test)

Example 80 with ClientProtocolException

use of org.apache.http.client.ClientProtocolException in project hadoop by apache.

the class WasbRemoteCallHelper method makeRemoteGetRequest.

/**
   * Helper method to make remote HTTP Get request.
   * @param getRequest - HttpGet request object constructed by caller.
   * @return Http Response body returned as a string. The caller
   *  is expected to semantically understand the response.
   * @throws WasbRemoteCallException
   * @throws IOException
   */
public String makeRemoteGetRequest(HttpGet getRequest) throws WasbRemoteCallException, IOException {
    try {
        final String APPLICATION_JSON = "application/json";
        final int MAX_CONTENT_LENGTH = 1024;
        getRequest.setHeader("Accept", APPLICATION_JSON);
        HttpResponse response = client.execute(getRequest);
        StatusLine statusLine = response.getStatusLine();
        if (statusLine == null || statusLine.getStatusCode() != HttpStatus.SC_OK) {
            throw new WasbRemoteCallException(getRequest.getURI().toString() + ":" + ((statusLine != null) ? statusLine.toString() : "NULL"));
        }
        Header contentTypeHeader = response.getFirstHeader("Content-Type");
        if (contentTypeHeader == null || contentTypeHeader.getValue() != APPLICATION_JSON) {
            throw new WasbRemoteCallException(getRequest.getURI().toString() + ":" + "Content-Type mismatch: expected: " + APPLICATION_JSON + ", got " + ((contentTypeHeader != null) ? contentTypeHeader.getValue() : "NULL"));
        }
        Header contentLengthHeader = response.getFirstHeader("Content-Length");
        if (contentLengthHeader == null) {
            throw new WasbRemoteCallException(getRequest.getURI().toString() + ":" + "Content-Length header missing");
        }
        try {
            if (Integer.parseInt(contentLengthHeader.getValue()) > MAX_CONTENT_LENGTH) {
                throw new WasbRemoteCallException(getRequest.getURI().toString() + ":" + "Content-Length:" + contentLengthHeader.getValue() + "exceeded max:" + MAX_CONTENT_LENGTH);
            }
        } catch (NumberFormatException nfe) {
            throw new WasbRemoteCallException(getRequest.getURI().toString() + ":" + "Invalid Content-Length value :" + contentLengthHeader.getValue());
        }
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8));
        StringBuilder responseBody = new StringBuilder();
        String responseLine = "";
        while ((responseLine = rd.readLine()) != null) {
            responseBody.append(responseLine);
        }
        rd.close();
        return responseBody.toString();
    } catch (ClientProtocolException clientProtocolEx) {
        throw new WasbRemoteCallException(getRequest.getURI().toString() + ":" + "Encountered ClientProtocolException while making remote call", clientProtocolEx);
    } catch (IOException ioEx) {
        throw new WasbRemoteCallException(getRequest.getURI().toString() + ":" + "Encountered IOException while making remote call", ioEx);
    }
}
Also used : StatusLine(org.apache.http.StatusLine) Header(org.apache.http.Header) InputStreamReader(java.io.InputStreamReader) BufferedReader(java.io.BufferedReader) HttpResponse(org.apache.http.HttpResponse) IOException(java.io.IOException) ClientProtocolException(org.apache.http.client.ClientProtocolException)

Aggregations

ClientProtocolException (org.apache.http.client.ClientProtocolException)92 IOException (java.io.IOException)80 HttpResponse (org.apache.http.HttpResponse)49 HttpPost (org.apache.http.client.methods.HttpPost)37 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)30 HttpClient (org.apache.http.client.HttpClient)29 HttpGet (org.apache.http.client.methods.HttpGet)25 HttpEntity (org.apache.http.HttpEntity)23 BasicNameValuePair (org.apache.http.message.BasicNameValuePair)20 UrlEncodedFormEntity (org.apache.http.client.entity.UrlEncodedFormEntity)19 InputStreamReader (java.io.InputStreamReader)18 ArrayList (java.util.ArrayList)18 UnsupportedEncodingException (java.io.UnsupportedEncodingException)17 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)14 BufferedReader (java.io.BufferedReader)13 InputStream (java.io.InputStream)13 NameValuePair (org.apache.http.NameValuePair)13 StringEntity (org.apache.http.entity.StringEntity)12 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)11 URI (java.net.URI)10