Example usage for org.apache.http.client.methods HttpPut setEntity

List of usage examples for org.apache.http.client.methods HttpPut setEntity

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpPut setEntity.

Prototype

public void setEntity(final HttpEntity entity) 

Source Link

Usage

From source file:com.hp.mercury.ci.jenkins.plugins.oo.core.OOAccessibilityLayer.java

public static int cancel10x(String urlString) throws IOException, InterruptedException {

    final URI uri = OOBuildStep.URI(urlString + EXECUTIONS_API + "/status");
    final HttpPut httpPut = new HttpPut(uri);
    String body = "{\"action\":\"cancel\"}";
    StringEntity entity = new StringEntity(body);
    httpPut.setEntity(entity);
    httpPut.setHeader("Content-Type", "application/json"); // this is mandatory in order for the request to work
    if (OOBuildStep.getEncodedCredentials() != null) {
        httpPut.addHeader("Authorization", "Basic " + new String(OOBuildStep.getEncodedCredentials()));
    }//from  w ww  .  ja v  a2  s.co m
    HttpResponse response = client.execute(httpPut);
    return response.getStatusLine().getStatusCode();
}

From source file:com.evrythng.java.wrapper.util.FileUtils.java

/**
 * Uploads text as a file content with PRIVATE read access.
 *
 * @param uri upload {@link URI}/*  w w w. ja va  2 s  .c o  m*/
 * @param contentTypeString content type
 * @param contentString text content
 * @throws IOException
 */
public static void uploadPrivateContent(final URI uri, final String contentTypeString,
        final String contentString) throws IOException {

    LOGGER.info("uploadPrivateContent START: uri: [{}]; content type: [{}], content length: [{}]",
            new Object[] { uri, contentTypeString, contentString.length() });

    CloseableHttpClient closeableHttpClient = HttpClients.createDefault();

    HttpPut httpPut = new HttpPut(uri);
    httpPut.addHeader(HttpHeaders.CONTENT_TYPE, contentTypeString);
    httpPut.addHeader(FileUtils.X_AMZ_ACL_HEADER_NAME, FileUtils.X_AMZ_ACL_HEADER_VALUE_PRIVATE);

    ContentType contentType = ContentType.create(contentTypeString);
    StringEntity stringEntity = new StringEntity(contentString, contentType);

    httpPut.setEntity(stringEntity);

    CloseableHttpResponse response = closeableHttpClient.execute(httpPut);
    StatusLine statusLine = response.getStatusLine();

    if (!(statusLine.getStatusCode() == HttpStatus.SC_OK)) {
        throw new IOException(String.format("An error occurred while trying to upload private file - %d: %s",
                statusLine.getStatusCode(), statusLine.getReasonPhrase()));
    }

    LOGGER.info("uploadPrivateContent END: uri: [{}]; content type: [{}], content length: [{}]",
            new Object[] { uri, contentTypeString, contentString.length() });
}

From source file:de.adesso.referencer.search.helper.ElasticConfig.java

public static String sendHttpRequest(String url, String requestBody, String requestType) throws IOException {
    String result = null;/*from  ww  w  . j a v  a2s. com*/
    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpResponse httpResponse;
    try {
        switch (requestType) {
        case "Get":
            httpResponse = httpclient.execute(new HttpGet(url));
            break;
        case "Post":
            HttpPost httppost = new HttpPost(url);
            if (requestBody != null)
                httppost.setEntity(new StringEntity(requestBody, DEFAULT_CHARSET));
            httpResponse = httpclient.execute(httppost);
            break;
        case "Put":
            HttpPut httpPut = new HttpPut(url);
            httpPut.addHeader("Content-Type", "application/json");
            httpPut.addHeader("Accept", "application/json");
            if (requestBody != null)
                httpPut.setEntity(new StringEntity(requestBody, DEFAULT_CHARSET));
            httpResponse = httpclient.execute(httpPut);
            break;
        case "Delete":
            httpResponse = httpclient.execute(new HttpDelete(url));
            break;
        default:
            httpResponse = httpclient.execute(new HttpGet(url));
            break;
        }
        try {
            HttpEntity entity1 = httpResponse.getEntity();
            if (entity1 != null) {
                long len = entity1.getContentLength();
                if (len != -1 && len < MAX_CONTENT_LENGTH) {
                    result = EntityUtils.toString(entity1, DEFAULT_CHARSET);
                } else {
                    System.out.println("Error!!!! entity length=" + len);
                }
            }
            EntityUtils.consume(entity1);
        } finally {
            httpResponse.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        httpclient.close();
    }
    return result;
}

From source file:com.investoday.code.util.aliyun.api.gateway.util.HttpUtil.java

/**
 * HTTP PUT?//w  ww .ja v a 2  s. c o m
 *
 * @param url                  http://host+path+query
 * @param headers              Http
 * @param formParam            ??
 * @param appKey               APP KEY
 * @param appSecret            APP
 * @param timeout              
 * @param signHeaderPrefixList ???Header?
 * @return 
 * @throws Exception
 */
public static HttpResponse httpPut(String url, Map<String, String> headers, Map<String, String> formParam,
        String appKey, String appSecret, int timeout, List<String> signHeaderPrefixList) throws Exception {
    headers = initialBasicHeader(headers, appKey, appSecret, HttpMethod.PUT, url, formParam,
            signHeaderPrefixList);
    HttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(timeout));

    HttpPut put = new HttpPut(url);
    for (Map.Entry<String, String> e : headers.entrySet()) {
        put.addHeader(e.getKey(), e.getValue());
    }

    UrlEncodedFormEntity formEntity = buildFormEntity(formParam);
    if (formEntity != null) {
        put.setEntity(formEntity);
    }

    return httpClient.execute(put);
}

From source file:com.lurencun.cfuture09.androidkit.http.Http.java

/**
 * ?PUT//www.j  a  va2  s  .c om
 *
 * @param uri
 *            URI
 * @param params
 *            ?
 * @return 
 * @throws IOException
 */
public static String put(String uri, BaseParams params) throws IOException {
    HttpPut request = new HttpPut(uri);
    if (params != null) {
        request.setEntity(new UrlEncodedFormEntity(params.getPairs()));
    }
    return sendRequest(request);
}

From source file:com.groupme.sdk.util.HttpUtils.java

public static InputStream openStream(HttpClient client, String url, int method, String body, Bundle params,
        Bundle headers) throws HttpResponseException {
    HttpResponse response;/*from w ww .ja  va  2s  . com*/
    InputStream in = null;

    Log.v("HttpUtils", "URL = " + url);

    try {
        switch (method) {
        case METHOD_GET:
            url = url + "?" + encodeParams(params);
            HttpGet get = new HttpGet(url);

            if (headers != null && !headers.isEmpty()) {
                for (String header : headers.keySet()) {
                    get.setHeader(header, headers.getString(header));
                }
            }

            response = client.execute(get);
            break;
        case METHOD_POST:
            if (body != null) {
                url = url + "?" + encodeParams(params);
            }

            HttpPost post = new HttpPost(url);
            Log.d(Constants.LOG_TAG, "URL: " + url);

            if (headers != null && !headers.isEmpty()) {
                for (String header : headers.keySet()) {
                    post.setHeader(header, headers.getString(header));
                }
            }

            if (body == null) {
                List<NameValuePair> pairs = bundleToList(params);
                post.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));
            } else {
                post.setEntity(new StringEntity(body));
            }

            response = client.execute(post);
            break;
        case METHOD_PUT:
            if (body != null) {
                url = url + "?" + encodeParams(params);
            }

            HttpPut put = new HttpPut(url);

            if (headers != null && !headers.isEmpty()) {
                for (String header : headers.keySet()) {
                    put.setHeader(header, headers.getString(header));
                }
            }

            if (body == null) {
                List<NameValuePair> pairs = bundleToList(params);
                put.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));
            } else {
                put.setEntity(new StringEntity(body));
            }

            response = client.execute(put);
            break;
        default:
            throw new UnsupportedOperationException("Cannot execute HTTP method: " + method);
        }

        int statusCode = response.getStatusLine().getStatusCode();

        if (statusCode > 400) {
            throw new HttpResponseException(statusCode, read(response.getEntity().getContent()));
        }

        in = response.getEntity().getContent();
    } catch (ClientProtocolException e) {
        Log.e(Constants.LOG_TAG, "Client error: " + e.toString());
    } catch (IOException e) {
        Log.e(Constants.LOG_TAG, "IO error: " + e.toString());
    }

    return in;
}

From source file:es.ucm.look.data.remote.restful.RestMethod.java

/**
 * To Update an element/*from   ww w  . j  a  v  a  2 s.  c  om*/
 * 
 * @param url
 *       Element URI
 * @param c
 *       The element to update represented with a JSON
 * @return
 *       The response
 */
public static HttpResponse doPut(String url, JSONObject c) {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPut request = new HttpPut(url);
    StringEntity s = null;
    try {
        s = new StringEntity(c.toString());
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    s.setContentEncoding("UTF-8");
    s.setContentType("application/json");

    request.setEntity(s);
    request.addHeader("accept", "application/json");

    try {
        return httpclient.execute(request);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;

}

From source file:org.escidoc.browser.elabsmodul.service.ELabsService.java

private static boolean sendStartRequest(final List<String[]> propertyList) {
    LOG.info("Service> Send configuration to start...");

    boolean hasError = false;

    Preconditions.checkNotNull(propertyList, "Config list is null");
    final String configURLPart = "/configuration";

    for (final String[] configurationArray : propertyList) {
        String esyncEndpoint = configurationArray[0];
        LOG.debug("Service> sending start request for " + esyncEndpoint);
        while (esyncEndpoint.endsWith("/")) {
            esyncEndpoint = esyncEndpoint.substring(0, esyncEndpoint.length() - 1);
        }//from www . ja v a 2 s .  co m

        if (!esyncEndpoint.endsWith(configURLPart)) {
            esyncEndpoint = esyncEndpoint + configURLPart;
        }

        try {
            LOG.debug("Service> called HttpClient.");
            // FIXME set proxy
            final DefaultHttpClient httpClient = new DefaultHttpClient();
            httpClient.setKeepAliveStrategy(null);
            final HttpPut putMethod = new HttpPut(esyncEndpoint);
            putMethod.setEntity(new StringEntity(configurationArray[1], HTTP.UTF_8));
            final HttpResponse response = httpClient.execute(putMethod);
            final StatusLine statusLine = response.getStatusLine();
            if (isNotSuccessful(statusLine.getStatusCode())) {
                LOG.error("Service> wrong method call: " + statusLine.getReasonPhrase());
                hasError = true;
            } else {
                LOG.info("Service> configuration is successfully sent!");
            }
        } catch (final UnsupportedEncodingException e) {
            LOG.error("Service> UnsupportedEncodingException: " + e.getMessage());
            hasError = true;
            continue;
        } catch (final ClientProtocolException e) {
            LOG.error("Service> ClientProtocolException: " + e.getMessage());
            hasError = true;
            continue;
        } catch (final IOException e) {
            LOG.error("Service> IOException: " + e.getMessage());
            hasError = true;
            continue;
        }
    }
    return hasError;
}

From source file:com.expertiseandroid.lib.sociallib.utils.Utils.java

/**
 * Sends a signed PUT request using the Signpost library
 * @param request the request's URL/*from   w  w w  .  j  a  v a2  s.c o m*/
 * @param entity the message's contents
 * @param consumer the Signpost consumer object
 * @param contentType the message's content type
 * @return the response
 * @throws OAuthMessageSignerException
 * @throws OAuthExpectationFailedException
 * @throws OAuthCommunicationException
 * @throws ClientProtocolException
 * @throws IOException
 */
public static ReadableResponse signedPutRequest(String request, String entity,
        CommonsHttpOAuthConsumer consumer, String contentType) throws OAuthMessageSignerException,
        OAuthExpectationFailedException, OAuthCommunicationException, ClientProtocolException, IOException {
    HttpClient client = new DefaultHttpClient();
    HttpPut put = new HttpPut(request);
    put.setEntity(new StringEntity(entity));
    put.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
    consumer.sign(put);
    put.addHeader("Content-Type", contentType);
    HttpResponse response = client.execute(put);
    return new HttpResponseWrapper(response);
}

From source file:com.expertiseandroid.lib.sociallib.utils.Utils.java

private static HttpRequestBase getRequestBaseByVerbEntity(String verb, String request, String entity)
        throws UnsupportedEncodingException {
    if (verb.equals(POST)) {
        HttpPost post = new HttpPost(request);
        post.setEntity(new StringEntity(entity));
        return post;
    } else if (verb.equals(GET))
        return new HttpGet(request);
    else if (verb.equals(PUT)) {
        HttpPut put = new HttpPut(request);
        put.setEntity(new StringEntity(entity));
        return put;
    } else if (verb.equals(DELETE))
        return new HttpDelete(request);
    else//from  w w  w . j av a2  s.com
        Log.e("Utils", "Cannot reckognize the verb " + verb);
    return null;
}