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.storageroomapp.client.util.Http.java

/**
 * PUT to the url with the body provided
 * @param url a String url//from  w  ww  . j  a  v a 2s .  c  o  m
 * @param body a String with text for the request body
 * @return true if successful (response code < 400), false otherwise
 */
static public boolean put(String url, String body) {
    boolean success = false;
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPut httpPut = new HttpPut(url);
        HttpEntity entity = new StringEntity(body);
        httpPut.setEntity(entity);

        // Be sure to add these headers or the StRoom API will NOT work! 
        Header contentType = new BasicHeader("Content-Type", "application/json");
        httpPut.setHeader(contentType);
        Header accept = new BasicHeader("Accept", "*/*");
        httpPut.setHeader(accept);

        HttpResponse response = httpclient.execute(httpPut);
        int code = response.getStatusLine().getStatusCode();
        success = code < 400;

        if (log.isDebugEnabled()) {
            String reason = response.getStatusLine().getReasonPhrase();
            log.debug("Http.post url [" + url + "] body [" + body + "] response code [" + code + "] reason ["
                    + reason + "]");
        }

    } catch (Exception e) {
        log.error("Http.put failed, with url [" + url + "]", e);
    }
    return success;
}

From source file:com.tek271.reverseProxy.servlet.ProxyFilter.java

/**
 * Helper method for passing post-requests
 */// w  w  w  .  j a  va  2s. c  o m
@SuppressWarnings({ "JavaDoc" })
private static HttpUriRequest createNewRequest(HttpServletRequest request, String newUrl) throws IOException {
    String method = request.getMethod();
    if (method.equals("POST")) {
        HttpPost httppost = new HttpPost(newUrl);
        if (ServletFileUpload.isMultipartContent(request)) {
            MultipartEntity entity = getMultipartEntity(request);
            httppost.setEntity(entity);
            addCustomHeaders(request, httppost, "Content-Type");
        } else {
            StringEntity entity = getEntity(request);
            httppost.setEntity(entity);
            addCustomHeaders(request, httppost);
        }
        return httppost;
    } else if (method.equals("PUT")) {
        StringEntity entity = getEntity(request);
        HttpPut httpPut = new HttpPut(newUrl);
        httpPut.setEntity(entity);
        addCustomHeaders(request, httpPut);
        return httpPut;
    } else if (method.equals("DELETE")) {
        StringEntity entity = getEntity(request);
        HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(newUrl);
        httpDelete.setEntity(entity);
        addCustomHeaders(request, httpDelete);
        return httpDelete;
    } else {
        HttpGet httpGet = new HttpGet(newUrl);
        addCustomGetHeaders(request, httpGet);
        return httpGet;
    }
}

From source file:com.google.resting.rest.client.BaseRESTClient.java

protected static HttpRequest buildHttpRequest(ServiceContext serviceContext) {

    String path = serviceContext.getPath();
    Verb verb = serviceContext.getVerb();
    HttpEntity httpEntity = serviceContext.getHttpEntity();
    List<Header> headers = serviceContext.getHeaders();

    if (verb == Verb.GET) {
        HttpGet httpGet = new HttpGet(path);
        if (headers != null) {
            for (Header header : headers)
                httpGet.addHeader(header);
        }/*from w  w w .j  a va  2 s  . co m*/
        return httpGet;

    } else if (verb == Verb.POST) {
        HttpPost httpPost = new HttpPost(path);
        if (headers != null) {
            for (Header header : headers)
                httpPost.addHeader(header);
        }
        if (httpEntity != null)
            httpPost.setEntity(httpEntity);
        return httpPost;

    } else if (verb == Verb.DELETE) {
        HttpDelete httpDelete = new HttpDelete(path);
        if (headers != null) {
            for (Header header : headers)
                httpDelete.addHeader(header);
        }
        return httpDelete;

    } else {
        HttpPut httpPut = new HttpPut(path);
        if (headers != null) {
            for (Header header : headers)
                httpPut.addHeader(header);
        }
        if (httpEntity != null)
            httpPut.setEntity(httpEntity);
        return httpPut;
    } //if
}

From source file:coolmapplugin.util.HTTPRequestUtil.java

public static boolean executePut(String targetURL, String jsonBody) {
    try (CloseableHttpClient httpClient = HttpClientBuilder.create().build()) {

        HttpPut request = new HttpPut(targetURL);

        if (jsonBody != null && !jsonBody.isEmpty()) {
            StringEntity params = new StringEntity(jsonBody);
            request.addHeader("content-type", "application/json");
            request.setEntity(params);
        }//from w  w w  . ja  v a  2  s .  c o  m

        HttpResponse result = httpClient.execute(request);

        if (result.getStatusLine().getStatusCode() == 412 || result.getStatusLine().getStatusCode() == 500) {
            return false;
        }

    } catch (IOException e) {
        return false;
    }

    return true;
}

From source file:org.wso2.bps.integration.tests.bpmn.BPMNTestUtils.java

public static HttpResponse doPut(String url, Object payload, String user, String password) throws IOException {
    String restUrl = getRestEndPoint(url);
    HttpClient client = new DefaultHttpClient();
    HttpPut put = new HttpPut(restUrl);
    put.addHeader(BasicScheme.authenticate(new UsernamePasswordCredentials(user, password), "UTF-8", false));
    put.setEntity(new StringEntity(payload.toString(), ContentType.APPLICATION_JSON));
    client.getConnectionManager().closeExpiredConnections();
    HttpResponse response = client.execute(put);
    return response;
}

From source file:io.openkit.OKHTTPClient.java

public static void putJSON(String relativeUrl, JSONObject requestParams,
        AsyncHttpResponseHandler responseHandler) {
    StringEntity sEntity = getJSONString(requestParams);
    HttpPut request = new HttpPut(getAbsoluteUrl(relativeUrl));

    if (sEntity == null) {
        responseHandler.onFailure(new Throwable("JSON encoding error"), "JSON encoding error");
    } else {/*from   ww w  .ja v a2  s  .  c om*/
        request.setEntity(sEntity);
        sign(request);
        client.put(request, "application/json", responseHandler);
    }
}

From source file:com.sugarcrm.candybean.webservices.WS.java

/**
 * Send a DELETE, GET, POST, or PUT http request
 *
 * @param op          The type of http request
 * @param uri         The http endpoint/*from   www . jav a2  s  .c  o m*/
 * @param headers     Map of header key value pairs
 * @param body        String representation of the request body
 * @param contentType The content type of the body
 * @return Key Value pairs of the response
 * @throws CandybeanException When http request failed
 */
public static Map<String, Object> request(OP op, String uri, Map<String, String> headers, String body,
        ContentType contentType) throws CandybeanException {
    switch (op) {
    case DELETE:
        return handleRequest(new HttpDelete(uri), headers);
    case GET:
        return handleRequest(new HttpGet(uri), headers);
    case POST:
        HttpPost post = new HttpPost(uri);
        if (body != null) {
            post.setEntity(new StringEntity(body, contentType));
        }
        return handleRequest(post, headers);
    case PUT:
        HttpPut put = new HttpPut(uri);
        if (body != null) {
            put.setEntity(new StringEntity(body, contentType));
        }
        return handleRequest(put, headers);
    default:
        /*
         * JLS 13.4.26: Adding or reordering constants in an enum type will not break compatibility with
         * pre-existing binaries.
         * Thus we include a default in the case that a future version of the enum has a case which is not
         * one of the above
         */
        throw new CandybeanException("Unrecognized OP type... Perhaps your binaries are the wrong version?");
    }
}

From source file:org.cloudsimulator.utility.RestAPI.java

private static CloseableHttpResponse putRequestBasicAuth(final CloseableHttpClient httpClient, final String uri,
        final String username, final String password, final String contentType, final HttpEntity entityToSend)
        throws IOException {
    HttpPut httpPut = new HttpPut(uri);
    httpPut.addHeader(CONTENTTYPE, contentType);
    httpPut.addHeader(AUTHORIZATION, getBasicAuth(username, password));
    httpPut.setEntity(entityToSend);
    return httpClient.execute(httpPut);
}

From source file:tech.beshu.ror.integration.ClosedIndicesTests.java

private static void insertDoc(String docName, RestClient restClient) {
    if (adminClient == null) {
        adminClient = restClient;//from ww  w .  j a va 2 s  .  c  om
    }

    String path = "/" + IDX_PREFIX + docName + "/documents/doc-" + docName;
    try {

        HttpPut request = new HttpPut(restClient.from(path));
        request.setHeader("Content-Type", "application/json");
        request.setHeader("refresh", "true");
        request.setHeader("timeout", "50s");
        request.setEntity(new StringEntity("{\"title\": \"" + docName + "\"}"));
        System.out.println(body(restClient.execute(request)));

    } catch (Exception e) {
        e.printStackTrace();
        throw new IllegalStateException("Test problem", e);
    }

    // Polling phase.. #TODO is there a better way?
    try {
        HttpResponse response;
        do {
            HttpHead request = new HttpHead(restClient.from(path));
            request.setHeader("x-api-key", "p");
            response = restClient.execute(request);
            System.out.println(
                    "polling for " + docName + ".. result: " + response.getStatusLine().getReasonPhrase());
            Thread.sleep(200);
        } while (response.getStatusLine().getStatusCode() != 200);
    } catch (Exception e) {
        e.printStackTrace();
        throw new IllegalStateException("Cannot configure test case", e);
    }
}

From source file:com.graphaware.test.util.TestUtils.java

/**
 * Issue an HTTP PUT and assert the response status code.
 *
 * @param url                to POST to.
 * @param json               request body.
 * @param headers            request headers as map.
 * @param expectedStatusCode expected status code.
 * @return the body of the response./*from   w  ww .  java  2s . c  o m*/
 */
public static String put(String url, String json, Map<String, String> headers, final int expectedStatusCode) {
    HttpPut put = new HttpPut(url);
    if (json != null) {
        put.setEntity(new StringEntity(json, ContentType.APPLICATION_JSON));
    }

    setHeaders(put, headers);

    return method(put, expectedStatusCode);
}