Example usage for org.apache.http.impl.client DefaultHttpClient getConnectionManager

List of usage examples for org.apache.http.impl.client DefaultHttpClient getConnectionManager

Introduction

In this page you can find the example usage for org.apache.http.impl.client DefaultHttpClient getConnectionManager.

Prototype

public synchronized final ClientConnectionManager getConnectionManager() 

Source Link

Usage

From source file:com.serena.rlc.provider.jenkins.client.JenkinsClient.java

/**
 * Send a POST and returns the Location header which contains the url to the queued item
 *
 * @param jenkinsUrl/*  www  .java2s.  c  o  m*/
 * @param postPath
 * @param postData
 * @return Response body
 * @throws JenkinsClientException
 */
public String processBuildPost(String jenkinsUrl, String postPath, String postData)
        throws JenkinsClientException {
    String uri = createUrl(jenkinsUrl, postPath);

    logger.debug("Start executing Jenkins POST request to url=\"{}\" with payload={}", uri);

    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpPost postRequest = new HttpPost(uri);

    if (getJenkinsUsername() != null && !StringUtils.isEmpty(getJenkinsUsername())) {
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(getJenkinsUsername(),
                getJenkinsPassword());
        postRequest.addHeader(BasicScheme.authenticate(creds, "US-ASCII", false));
    }

    postRequest.addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");
    postRequest.addHeader(HttpHeaders.ACCEPT, "application/json");
    String result = "";

    List<NameValuePair> params = new ArrayList<>();
    params.add(new BasicNameValuePair("json", postData));

    try {

        postRequest.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));

        HttpResponse response = httpClient.execute(postRequest);
        if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK
                && response.getStatusLine().getStatusCode() != HttpStatus.SC_CREATED) {
            throw createHttpError(response);
        }

        result = response.getFirstHeader("Location").getValue();

        logger.debug("End executing Jenkins POST request to url=\"{}\" and receive this result={}", uri,
                result);

    } catch (IOException e) {
        logger.error(e.getMessage(), e);
        throw new JenkinsClientException("Server not available", e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    return result;
}

From source file:org.miloss.fgsms.bueller.Bueller.java

/**
 * attempts an http get request with authentication
 *
 * @param pooled/*ww w .j a v a 2 s .  c  o m*/
 * @param endpoint
 * @param policyURL
 * @return
 */
protected String sendGetRequestAuth(boolean pooled, String endpoint, String policyURL, int depth) {//, AuthMode mode) {
    if (depth > 10) {
        //abort, possible redirect loop
        return "Aborting due to redirect loop";
    }
    String[] info = DBSettingsLoader.GetCredentials(pooled, policyURL);

    if (info == null) {
        info = DBSettingsLoader.GetDefaultBuellerCredentials(pooled);
        if (info == null) {
            return "Unauthorized, no credentials are available";
        }
    }

    if (endpoint.startsWith("http://")) {
        // Send a GET request to the servlet

        DefaultHttpClient c = new DefaultHttpClient();
        try {
            c.getCredentialsProvider().setCredentials(AuthScope.ANY, transformCredentials(info));
            if (!c.getCredentialsProvider().getCredentials(AuthScope.ANY).getClass().getCanonicalName().equalsIgnoreCase(NTCredentials.class.getCanonicalName())) {
                log.log(Level.WARN, "Usage of non-NTLM authentication over a non SSL channel.");
            }
            HttpGet m = new HttpGet(endpoint);
            HttpResponse res = c.execute(m);
            int status = res.getStatusLine().getStatusCode();
            try {
                InputStream content = res.getEntity().getContent();
                byte[] buffer = new byte[1024];
                while (content.read(buffer) >= 0) {
                }
            } catch (Exception f) {
            }
            c.getConnectionManager().shutdown();
            if (status < 300 || status == HttpStatus.SC_NOT_MODIFIED) {
                return "OK";
            } else if (status == HttpStatus.SC_MOVED_PERMANENTLY
                    || status == HttpStatus.SC_TEMPORARY_REDIRECT
                    || status == HttpStatus.SC_MOVED_TEMPORARILY) {
                String newUrl = res.getHeaders("Location")[0].getValue();
                return sendGetRequestAuth(pooled, newUrl, policyURL, depth + 1);
            }

            return String.valueOf(status);
        } catch (Exception ex) {
            c.getConnectionManager().shutdown();
            log.log(Level.INFO, "code " + ex.getLocalizedMessage());
            return "offline: " + ex.getMessage();
        }
    } else if (endpoint.startsWith("https://")) {

        //first try with the username/password over ssl
        if (sf == null && sfpki == null) {
            return "Unauthorized, no trust store available for SSL communication";
        }
        DefaultHttpClient c = new DefaultHttpClient();
        try {
            URL url = new URL(endpoint);
            String scheme = "https";
            int port = url.getPort();

            if (port == -1 && endpoint.toLowerCase().startsWith("https:")) {
                port = 443;
            }

            Scheme sch = null;

            if (sfpki == null) {
                sch = new Scheme("https", port, sf);
            } else {
                sch = new Scheme("https", port, sfpki);
            }
            c.getConnectionManager().getSchemeRegistry().register(sch);

            c.getCredentialsProvider().setCredentials(AuthScope.ANY, transformCredentials(info));

            HttpGet m = new HttpGet(endpoint);
            HttpResponse res = c.execute(m);
            int status = res.getStatusLine().getStatusCode();
            try {
                InputStream content = res.getEntity().getContent();
                byte[] buffer = new byte[1024];
                while (content.read(buffer) >= 0) {
                }
            } catch (Exception f) {
            }
            c.getConnectionManager().shutdown();
            if (status < 300 || status == HttpStatus.SC_NOT_MODIFIED) {
                return "OK";
            } else if (status == HttpStatus.SC_MOVED_PERMANENTLY
                    || status == HttpStatus.SC_TEMPORARY_REDIRECT
                    || status == HttpStatus.SC_MOVED_TEMPORARILY) {
                String newUrl = res.getHeaders("Location")[0].getValue();
                return sendGetRequestAuth(pooled, newUrl, policyURL, depth + 1);
            }

            return String.valueOf(status);
        } catch (Exception ex) {
            c.getConnectionManager().shutdown();
            log.log(Level.INFO, "code " + ex.getLocalizedMessage());
            return "offline: " + ex.getMessage();
        }

    } else {
        return "undeterminable";
    }

}

From source file:org.webservice.fotolia.FotoliaApi.java

/**
 * Call a methof of the Fotolia API/*  w w w  .  ja  va2 s.  c  om*/
 *
 * @param  method_name
 * @param  args
 * @param  auto_refresh_token
 * @return JSONObject
 */
private JSONObject _api(final String method_name, final FotoliaApiArgs args, final boolean auto_refresh_token) {
    DefaultHttpClient client;
    FotoliaApiResponse responseHandler;
    JSONObject response = null;

    client = this._getHttpClient(auto_refresh_token);

    try {
        responseHandler = new FotoliaApiResponse();
        response = (JSONObject) JSONValue
                .parse(client.execute(this._getMethod(method_name, args), responseHandler).toString());
    } catch (Exception e) {
        System.out.println("Exception while retrieving data : " + e);
    } finally {
        client.getConnectionManager().shutdown();
    }

    return response;
}

From source file:org.jboss.as.test.clustering.cluster.ejb3.stateful.StatefulFailoverTestCase.java

@Test
public void testRestart(@ArquillianResource() @OperateOnDeployment(DEPLOYMENT_1) URL baseURL1,
        @ArquillianResource() @OperateOnDeployment(DEPLOYMENT_2) URL baseURL2)
        throws IOException, InterruptedException, URISyntaxException {

    // Only needed for injection
    stop(CONTAINER_2);/*www . j a  v a  2 s  .  c om*/

    DefaultHttpClient client = org.jboss.as.test.http.util.HttpClientUtils.relaxedCookieHttpClient();

    String url1 = baseURL1.toString() + "count";
    String url2 = baseURL2.toString() + "count";

    log.info("URLs are: " + url1 + ", " + url2);

    try {
        assertEquals(20010101, this.queryCount(client, url1));
        assertEquals(20020202, this.queryCount(client, url1));

        start(CONTAINER_2);

        assertEquals(20030303, this.queryCount(client, url1));
        assertEquals(20040404, this.queryCount(client, url1));

        assertEquals(20050505, this.queryCount(client, url2));
        assertEquals(20060606, this.queryCount(client, url2));

        stop(CONTAINER_2);

        assertEquals(20070707, this.queryCount(client, url1));
        assertEquals(20080808, this.queryCount(client, url1));

        start(CONTAINER_2);

        assertEquals(20090909, this.queryCount(client, url1));
        assertEquals(20101010, this.queryCount(client, url1));

        assertEquals(20111111, this.queryCount(client, url2));
        assertEquals(20121212, this.queryCount(client, url2));

        stop(CONTAINER_1);

        assertEquals(20131313, this.queryCount(client, url2));
        assertEquals(20141414, this.queryCount(client, url2));

        start(CONTAINER_1);

        assertEquals(20151515, this.queryCount(client, url1));
        assertEquals(20161616, this.queryCount(client, url1));

        assertEquals(20171717, this.queryCount(client, url1));
        assertEquals(20181818, this.queryCount(client, url1));
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:org.squale.squalerest.client.SqualeRestHttpClient.java

/**
 * This method executes the search//from ww  w  .  ja  va 2 s.com
 * 
 * @param path The query
 * @param xstream The xstream processor
 * @return The object result of the query
 * @throws SqualeRestException Exception occurs during the serach
 */
private Object execute(String path, XStream xstream) throws SqualeRestException {
    Object objectToReturn = null;
    DefaultHttpClient httpclient = null;
    try {
        httpclient = new DefaultHttpClient();

        // Create credentials
        UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user, password);
        httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY, creds);

        // Define the host
        HttpHost targetHost = new HttpHost(host, port);

        // Define the get method
        HttpGet httpget = new HttpGet(path);

        // Execute the request
        HttpResponse response = httpclient.execute(targetHost, httpget);
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream is = null;
                try {
                    // Transform the xml stream into java object
                    is = entity.getContent();
                    objectToReturn = xstream.fromXML(is);
                } finally {
                    // In all case close the input stream
                    if (is != null) {
                        is.close();
                    }
                }
            }
        } else {
            throw new SqualeRestException(response.getStatusLine().getStatusCode() + " : "
                    + response.getStatusLine().getReasonPhrase());
        }
    } catch (ClientProtocolException e) {
        throw new SqualeRestException(e);
    } catch (IOException e) {
        throw new SqualeRestException(e);
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
    return objectToReturn;
}

From source file:com.box.androidlib.BoxFileUpload.java

/**
 * Execute a file upload.//from   w w  w . ja  v  a2  s.  c o  m
 * 
 * @param action
 *            Set to {@link com.box.androidlib.Box#UPLOAD_ACTION_UPLOAD} or {@link com.box.androidlib.Box#UPLOAD_ACTION_OVERWRITE} or
 *            {@link com.box.androidlib.Box#UPLOAD_ACTION_NEW_COPY}
 * @param sourceInputStream
 *            Input stream targeting the data for the file you wish to create/upload to Box.
 * @param filename
 *            The desired filename on Box after upload (just the file name, do not include the path)
 * @param destinationId
 *            If action is {@link com.box.androidlib.Box#UPLOAD_ACTION_UPLOAD}, then this is the folder id where the file will uploaded to. If action is
 *            {@link com.box.androidlib.Box#UPLOAD_ACTION_OVERWRITE} or {@link com.box.androidlib.Box#UPLOAD_ACTION_NEW_COPY}, then this is the file_id that
 *            is being overwritten, or copied.
 * @return A FileResponseParser with information about the upload.
 * @throws IOException
 *             Can be thrown if there is no connection, or if some other connection problem exists.
 * @throws FileNotFoundException
 *             File being uploaded either doesn't exist, is not a file, or cannot be read
 * @throws MalformedURLException
 *             Make sure you have specified a valid upload action
 */
public FileResponseParser execute(final String action, final InputStream sourceInputStream,
        final String filename, final long destinationId)
        throws IOException, MalformedURLException, FileNotFoundException {

    if (!action.equals(Box.UPLOAD_ACTION_UPLOAD) && !action.equals(Box.UPLOAD_ACTION_OVERWRITE)
            && !action.equals(Box.UPLOAD_ACTION_NEW_COPY)) {
        throw new MalformedURLException("action must be upload, overwrite or new_copy");
    }

    final Uri.Builder builder = new Uri.Builder();
    builder.scheme(BoxConfig.getInstance().getUploadUrlScheme());
    builder.encodedAuthority(BoxConfig.getInstance().getUploadUrlAuthority());
    builder.path(BoxConfig.getInstance().getUploadUrlPath());
    builder.appendPath(action);
    builder.appendPath(mAuthToken);
    builder.appendPath(String.valueOf(destinationId));
    if (action.equals(Box.UPLOAD_ACTION_OVERWRITE)) {
        builder.appendQueryParameter("file_name", filename);
    } else if (action.equals(Box.UPLOAD_ACTION_NEW_COPY)) {
        builder.appendQueryParameter("new_file_name", filename);
    }

    List<BasicNameValuePair> customQueryParams = BoxConfig.getInstance().getCustomQueryParameters();
    if (customQueryParams != null && customQueryParams.size() > 0) {
        for (BasicNameValuePair param : customQueryParams) {
            builder.appendQueryParameter(param.getName(), param.getValue());
        }
    }

    if (BoxConfig.getInstance().getHttpLoggingEnabled()) {
        //            DevUtils.logcat("Uploading : " + filename + "  Action= " + action + " DestinionID + " + destinationId);
        DevUtils.logcat("Upload URL : " + builder.build().toString());
    }
    // Set up post body
    final HttpPost post = new HttpPost(builder.build().toString());
    final MultipartEntityWithProgressListener reqEntity = new MultipartEntityWithProgressListener(
            HttpMultipartMode.BROWSER_COMPATIBLE, null, Charset.forName(HTTP.UTF_8));

    if (mListener != null && mHandler != null) {
        reqEntity.setProgressListener(new MultipartEntityWithProgressListener.ProgressListener() {

            @Override
            public void onTransferred(final long bytesTransferredCumulative) {
                mHandler.post(new Runnable() {

                    @Override
                    public void run() {
                        mListener.onProgress(bytesTransferredCumulative);
                    }
                });
            }
        });
    }

    reqEntity.addPart("file_name", new InputStreamBody(sourceInputStream, filename) {

        @Override
        public String getFilename() {
            return filename;
        }
    });
    post.setEntity(reqEntity);

    // Send request
    final HttpResponse httpResponse;
    DefaultHttpClient httpClient = new DefaultHttpClient();
    HttpProtocolParams.setUserAgent(httpClient.getParams(), BoxConfig.getInstance().getUserAgent());
    post.setHeader("Accept-Language", BoxConfig.getInstance().getAcceptLanguage());
    try {
        httpResponse = httpClient.execute(post);
    } catch (final IOException e) {
        // Detect if the download was cancelled through thread interrupt. See CountingOutputStream.write() for when this exception is thrown.
        if (BoxConfig.getInstance().getHttpLoggingEnabled()) {
            //                DevUtils.logcat("IOException Uploading " + filename + " Exception Message: " + e.getMessage() + e.toString());
            DevUtils.logcat(" Exception : " + e.toString());
            e.printStackTrace();
            DevUtils.logcat("Upload URL : " + builder.build().toString());
        }
        if ((e.getMessage() != null && e.getMessage().equals(FileUploadListener.STATUS_CANCELLED))
                || Thread.currentThread().isInterrupted()) {
            final FileResponseParser handler = new FileResponseParser();
            handler.setStatus(FileUploadListener.STATUS_CANCELLED);
            return handler;
        } else {
            throw e;
        }
    } finally {
        if (httpClient != null && httpClient.getConnectionManager() != null) {
            httpClient.getConnectionManager().closeIdleConnections(500, TimeUnit.MILLISECONDS);
        }
    }
    if (BoxConfig.getInstance().getHttpLoggingEnabled()) {
        DevUtils.logcat("HTTP Response Code: " + httpResponse.getStatusLine().getStatusCode());
        Header[] headers = httpResponse.getAllHeaders();
        //            DevUtils.logcat("User-Agent : " + HttpProtocolParams.getUserAgent(httpClient.getParams()));
        //            for (Header header : headers) {
        //                DevUtils.logcat("Response Header: " + header.toString());
        //            }
    }

    // Server returned a 503 Service Unavailable. Usually means a temporary unavailability.
    if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_SERVICE_UNAVAILABLE) {
        final FileResponseParser handler = new FileResponseParser();
        handler.setStatus(ResponseListener.STATUS_SERVICE_UNAVAILABLE);
        return handler;
    }

    String status = null;
    BoxFile boxFile = null;
    final InputStream is = httpResponse.getEntity().getContent();
    final BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    final StringBuilder sb = new StringBuilder();
    String line = null;
    while ((line = reader.readLine()) != null) {
        sb.append(line);
    }
    is.close();
    httpResponse.getEntity().consumeContent();
    final String xml = sb.toString();

    try {
        final Document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                .parse(new ByteArrayInputStream(xml.getBytes()));
        final Node statusNode = doc.getElementsByTagName("status").item(0);
        if (statusNode != null) {
            status = statusNode.getFirstChild().getNodeValue();
        }
        final Element fileEl = (Element) doc.getElementsByTagName("file").item(0);
        if (fileEl != null) {
            try {
                boxFile = Box.getBoxFileClass().newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            for (int i = 0; i < fileEl.getAttributes().getLength(); i++) {
                boxFile.parseAttribute(fileEl.getAttributes().item(i).getNodeName(),
                        fileEl.getAttributes().item(i).getNodeValue());
            }
        }

        // errors are NOT returned as properly formatted XML yet so in this case the raw response is the error status code see
        // http://developers.box.net/w/page/12923951/ApiFunction_Upload-and-Download
        if (status == null) {
            status = xml;
        }
    } catch (final SAXException e) {
        // errors are NOT returned as properly formatted XML yet so in this case the raw response is the error status code see
        // http://developers.box.net/w/page/12923951/ApiFunction_Upload-and-Download
        status = xml;
    } catch (final ParserConfigurationException e) {
        e.printStackTrace();
    }
    final FileResponseParser handler = new FileResponseParser();
    handler.setFile(boxFile);
    handler.setStatus(status);
    return handler;
}

From source file:org.altchain.neo4j.bitcoind.BitcoinD.java

private JSONObject invokeRPC(String JSONRequestString) throws BitcoindNotRunningException {
    DefaultHttpClient httpclient = new DefaultHttpClient();

    JSONObject responseJsonObj = null;/* w  w  w  .j  a va2  s .  co m*/

    try {

        httpclient.getCredentialsProvider().setCredentials(new AuthScope(bitcoindHost, bitcoindPort),
                new UsernamePasswordCredentials("generated_by_armory",
                        "6nkugwdEacEAgqjbCvvVyrgXcZj5Cxr38vTbZ513QJrf"));

        StringEntity myEntity = new StringEntity(JSONRequestString);
        logger.debug("JSON Request Object: " + JSONRequestString);

        HttpPost httppost = new HttpPost("http://" + this.bitcoindHost + ":" + this.bitcoindPort);
        httppost.setEntity(myEntity);

        logger.debug("executing request: " + httppost.getRequestLine());

        HttpEntity entity = null;

        try {

            HttpResponse response = httpclient.execute(httppost);
            entity = response.getEntity();

            logger.debug("HTTP response: " + response.getStatusLine());

        } catch (Exception e) {
            logger.error("CANNOT CONNECT TO BITCOIND.  IS BITCOIN RUNNING?");
            throw new BitcoindNotRunningException();
        }

        if (entity != null) {

            logger.debug("Response content length: " + entity.getContentLength());

        }

        JSONParser parser = new JSONParser();
        responseJsonObj = (JSONObject) parser.parse(EntityUtils.toString(entity));

    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException e) {
        e.printStackTrace();
    } catch (org.json.simple.parser.ParseException e) {
        e.printStackTrace();
    } finally {

        httpclient.getConnectionManager().shutdown();

    }

    return responseJsonObj;

}

From source file:no.kantega.kwashc.server.test.ImproperErrorHandlingTest.java

@Override
protected TestResult testSite(Site site, TestResult testResult) throws Throwable {
    long startTime = System.nanoTime();

    DefaultHttpClient httpclient = new DefaultHttpClient();
    String responseBody = "";
    String responseBody2 = "";

    try {/*ww w  .ja  v a2 s  .com*/
        HttpPost request = new HttpPost(site.getAddress() + "doLogin?username=username&password=%E6%E6%27");
        HttpResponse response = httpclient.execute(request);
        int statusCode = response.getStatusLine().getStatusCode();
        HttpEntity entity = response.getEntity();
        responseBody = EntityUtils.toString(entity);

        if (responseBody.contains("Exception") || responseBody.contains("exception")
                || responseBody.contains("Caused by") || responseBody.contains("caused by")) {
            testResult.setResultEnum(ResultEnum.failed);
            testResult.setMessage("The application gives an attacker very useful feedback on attempted attacks "
                    + "by displaying detailed error messages and stack traces.");
        } else if (statusCode == 500 || statusCode == 200) {

            HttpGet request2 = new HttpGet(site.getAddress() + "...");
            HttpResponse response2 = httpclient.execute(request2);
            int statusCode2 = response2.getStatusLine().getStatusCode();

            if (statusCode2 == 404 || statusCode2 == 200) {
                testResult.setResultEnum(ResultEnum.passed);
                testResult.setMessage(
                        "Ok, your application handles errors codes and tries not to leak " + "information!");
            }
        } else {
            testResult.setResultEnum(ResultEnum.error);
            testResult.setMessage("The test didn't work properly, are you providing a proper and secure error "
                    + "handling?");
        }
    } finally {
        httpclient.getConnectionManager().shutdown();
    }

    setDuration(testResult, startTime);
    return testResult;
}

From source file:de.unikassel.android.sdcframework.transmission.SimpleHttpProtocol.java

/**
 * Method for an HTTP upload of file stream
 * //from  ww  w .j av  a2 s . c o  m
 * @param file
 *          the input file
 * 
 * @return true if successful, false otherwise
 */
private final boolean httpUpload(File file) {
    DefaultHttpClient client = new DefaultHttpClient();

    try {
        String fileName = FileUtils.fileNameFromPath(file.getName());
        String contentType = getContentType(fileName);

        URL url = getURL();
        configureForAuthentication(client, url);

        HttpPost httpPost = new HttpPost(url.toURI());

        FileEntity fileEntity = new FileEntity(file, contentType);
        fileEntity.setContentType(contentType);
        fileEntity.setChunked(true);

        httpPost.setEntity(fileEntity);
        httpPost.addHeader("filename", fileName);
        httpPost.addHeader("uuid", getUuid().toString());

        HttpResponse response = client.execute(httpPost);

        int statusCode = response.getStatusLine().getStatusCode();
        boolean success = statusCode == HttpStatus.SC_OK || statusCode == HttpStatus.SC_NO_CONTENT;
        Logger.getInstance().debug(this, "Server returned: " + statusCode);

        // clean up if necessary
        HttpEntity resEntity = response.getEntity();
        if (resEntity != null) {
            resEntity.consumeContent();
        }

        if (!success) {
            doHandleError("Unexpected server response: " + response.getStatusLine());
            success = false;
        }

        return success;
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        doHandleError(PROTOCOL_EXCEPTION + ": " + e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        doHandleError(IO_EXCEPTION + ": " + e.getMessage());
    } catch (URISyntaxException e) {
        setURL(null);
        doHandleError(INVALID_URL);
    } finally {
        client.getConnectionManager().shutdown();
    }
    return false;
}

From source file:uk.ac.diamond.scisoft.feedback.FeedbackRequest.java

/**
 * Method used to submit a form data/file through HTTP to a GAE servlet
 * /*  www  .jav  a 2  s  . c om*/
 * @param email
 * @param to
 * @param name
 * @param subject
 * @param messageBody
 * @param attachmentFiles
 * @param monitor
 */
public static IStatus doRequest(String email, String to, String name, String subject, String messageBody,
        List<File> attachmentFiles, IProgressMonitor monitor) throws Exception {
    Status status = null;
    DefaultHttpClient httpclient = new DefaultHttpClient();

    FeedbackProxy.init();
    host = FeedbackProxy.getHost();
    port = FeedbackProxy.getPort();

    if (monitor.isCanceled())
        return Status.CANCEL_STATUS;

    // if there is a proxy
    if (host != null) {
        HttpHost proxy = new HttpHost(host, port);
        httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
    }

    if (monitor.isCanceled())
        return Status.CANCEL_STATUS;

    try {
        HttpPost httpost = new HttpPost(SERVLET_URL + SERVLET_NAME);

        MultipartEntity entity = new MultipartEntity();
        entity.addPart("name", new StringBody(name));
        entity.addPart("email", new StringBody(email));
        entity.addPart("to", new StringBody(to));
        entity.addPart("subject", new StringBody(subject));
        entity.addPart("message", new StringBody(messageBody));

        // add attachement files to the multipart entity
        for (int i = 0; i < attachmentFiles.size(); i++) {
            if (attachmentFiles.get(i) != null && attachmentFiles.get(i).exists())
                entity.addPart("attachment" + i + ".html", new FileBody(attachmentFiles.get(i)));
        }

        if (monitor.isCanceled())
            return Status.CANCEL_STATUS;

        httpost.setEntity(entity);

        // HttpPost post = new HttpPost("http://dawnsci-feedback.appspot.com/dawnfeedback?name=baha&email=baha@email.com&subject=thisisasubject&message=thisisthemessage");
        HttpResponse response = httpclient.execute(httpost);

        if (monitor.isCanceled())
            return Status.CANCEL_STATUS;

        final String reasonPhrase = response.getStatusLine().getReasonPhrase();
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == 200) {
            logger.debug("Status code 200");
            status = new Status(IStatus.OK, "Feedback successfully sent", "Thank you for your contribution");
        } else {
            logger.debug("Feedback email not sent - HTTP response: " + reasonPhrase);
            status = new Status(IStatus.WARNING, "Feedback not sent",
                    "The response from the server is the following:\n" + reasonPhrase
                            + "\nClick on OK to submit your feedback using the online feedback form available at http://dawnsci-feedback.appspot.com/");
        }
        logger.debug("HTTP Response: " + response.getStatusLine());
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
    }
    return status;
}