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:org.sharetask.controller.WorkspaceControllerIT.java

@Test
public void testChangeOwnerWorkspace() throws IOException {
    //given//from ww  w .  j a  v a 2s . co  m
    final HttpPut httpPut = new HttpPut(URL_WORKSPACE);
    httpPut.addHeader(new BasicHeader("Content-Type", "application/json"));
    final StringEntity httpEntity = new StringEntity(
            "{\"id\":3," + "\"title\":\"Test Title\"," + "\"owner\":{\"username\":\"dev2@shareta.sk\"}" + "}");
    httpPut.setEntity(httpEntity);

    //when
    final HttpResponse response = getClient().execute(httpPut);

    //then
    Assert.assertEquals(HttpStatus.OK.value(), response.getStatusLine().getStatusCode());
    final String responseData = EntityUtils.toString(response.getEntity());
    Assert.assertTrue(responseData.contains("\"username\":\"dev2@shareta.sk\""));
}

From source file:io.kyligence.benchmark.loadtest.client.RestClient.java

private boolean changeCubeStatus(String url) throws Exception {
    HttpPut put = newPut(url);
    HashMap<String, String> paraMap = new HashMap<String, String>();
    String jsonMsg = new ObjectMapper().writeValueAsString(paraMap);
    put.setEntity(new StringEntity(jsonMsg, "UTF-8"));
    HttpResponse response = client.execute(put);
    String result = getContent(response);
    if (response.getStatusLine().getStatusCode() != 200) {
        throw new IOException("Invalid response " + response.getStatusLine().getStatusCode() + " with url "
                + url + "\n" + jsonMsg);
    } else {/*from  ww  w  .j a va  2  s .c  o m*/
        return true;
    }
}

From source file:WSpatern.LoginWS.java

public void getLoginAuth(String user, String password) {
    try {/*  www.j  a  v  a  2  s  . co  m*/
        DefaultHttpClient client = new DefaultHttpClient();
        HttpPut putRequest = new HttpPut("https://documenta-dms.com/DMSWS/api/v1/login/");

        StringEntity input = new StringEntity("<user>\n" + "<username>" + user + "</username>\n" + "<password>"
                + password + "</password>\n" + "</user>");
        input.setContentType("application/xml");
        System.out.println("Out Put Of WS " + input);
        putRequest.setEntity(input);
        HttpResponse response = client.execute(putRequest);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line = null;
        while ((line = rd.readLine()) != null) {

            System.out.println(line);
            if (!line.contains("<html>")) {
                parseXML(line);
            } else {
                valid = false;
            }

        }
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(LoginWS.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(LoginWS.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:utils.XMSRestSender.java

public String PUT(String dest, String xmlpayload) {

    //HttpResponse - After receiving and interpreting a request message, a server responds with an HTTP response message.
    //Response      = Status-Line
    //             *(( general-header
    //              | response-header
    //              | entity-header ) CRLF)
    //             CRLF
    //             [ message-body ]
    //http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/HttpResponse.html?is-external=true
    HttpResponse response = null;//from  ww w.j  a  v a 2s  . com

    //This string is used to store the XML extracted from the Response
    String xmlresponse = "";
    try {

        System.out.println("PUT " + dest + "?appid=" + appid + "\n XMLPayload:\n" + xmlpayload);
        //HttpPut -  HTTP PUT method.
        // The HTTP PUT method is defined in section 9.6 of RFC2616:
        //http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/methods/HttpPut.html
        // In XMS the PUT is used to cause action or update on an existing resource (ie media functionality, joining etc)

        // The PUT requires an XML payload.  This block will convert the passed XML String to an http Entitiy and 
        // attach it to the post message.  Will also update the header to indicate the format of the payload is XML
        StringEntity se = new StringEntity(xmlpayload, HTTP.UTF_8);
        HttpPut httpput = new HttpPut(dest + "?appid=" + appid);
        httpput.setHeader("Content-Type", "text/xml;charset=UTF-8");
        httpput.setEntity(se);

        //Here you are issueing the PUT Request, to the provided host via the HttpClient and storing
        //  the response in the HpptResponse
        response = httpclient.execute(host, httpput);

        //HttpEntity - An entity that can be sent or received with an HTTP message. 
        // Entities can be found in some requests and in responses, where they are optional.
        // http://hc.apache.org/httpcomponents-core-ga/httpcore/apidocs/org/apache/http/HttpEntity.html
        HttpEntity entity = response.getEntity();

        //This block will dump out the Status, headers and message contents if available
        System.out.println(response.getStatusLine());
        Header[] headers = response.getAllHeaders();
        for (int i = 0; i < headers.length; i++) {
            System.out.println("   " + headers[i]);
        }
        System.out.println("****** Message Contents *******");

        if (entity != null) {
            xmlresponse = EntityUtils.toString(entity);
            System.out.println(xmlresponse);
        }
    } catch (IOException ex) {
        Logger.getLogger(XMSRestSender.class.getName()).log(Level.SEVERE, null, ex);
    }

    return xmlresponse;
}

From source file:code.google.restclient.core.Hitter.java

/**
 * Method to make POST or PUT request by sending http entity (as body)
 *///  w  w  w .j  a  v a2  s .c o  m
public void hit(String url, String methodName, HttpHandler handler, Map<String, String> requestHeaders)
        throws Exception {

    if (DEBUG_ENABLED)
        LOG.debug("hit() - method => " + methodName + ", url => " + url);

    if (HttpGet.METHOD_NAME.equals(methodName)) {
        if (DEBUG_ENABLED)
            LOG.debug("hit() - ===> GET " + url);
        hit(url, new HttpGet(url), handler, requestHeaders);
    } else if (HttpHead.METHOD_NAME.equals(methodName)) {
        if (DEBUG_ENABLED)
            LOG.debug("hit() - ===> HEAD " + url);
        hit(url, new HttpHead(url), handler, requestHeaders);
    } else if (HttpDelete.METHOD_NAME.equals(methodName)) {
        if (DEBUG_ENABLED)
            LOG.debug("hit() - ===> DELETE " + url);
        hit(url, new HttpDelete(url), handler, requestHeaders);
    } else if (HttpOptions.METHOD_NAME.equals(methodName)) {
        if (DEBUG_ENABLED)
            LOG.debug("hit() - ===> OPTIONS " + url);
        hit(url, new HttpOptions(url), handler, requestHeaders);
    } else if (HttpTrace.METHOD_NAME.equals(methodName)) {
        if (DEBUG_ENABLED)
            LOG.debug("hit() - ===> TRACE " + url);
        hit(url, new HttpTrace(url), handler, requestHeaders);
    } else if (HttpPost.METHOD_NAME.equals(methodName)) { // POST
        if (DEBUG_ENABLED)
            LOG.debug("hit() - ===> POST " + url);
        HttpPost httpPost = new HttpPost(url);
        httpPost.setEntity(handler.getReqBodyEntity());
        hit(url, httpPost, handler, requestHeaders);
    } else if (HttpPut.METHOD_NAME.equals(methodName)) { // PUT
        if (DEBUG_ENABLED)
            LOG.debug("hit() - ===> PUT " + url);
        HttpPut httpPut = new HttpPut(url);
        httpPut.setEntity(handler.getReqBodyEntity());
        hit(url, httpPut, handler, requestHeaders);
    } else {
        throw new IllegalArgumentException("hit(): Unsupported method => " + methodName);
    }
}

From source file:org.bitrepository.protocol.http.HttpFileExchange.java

/**
 * Method for putting data on the HTTP-server of a given url.
 * //from   www  .  ja  v  a 2  s.  c  o  m
 * TODO perhaps make it synchronized around the URL, to prevent data from 
 * trying to uploaded several times to the same location simultaneously. 
 * 
 * @param in The data to put into the url.
 * @param url The place to put the data.
 * @throws IOException If a problem with the connection occurs during the 
 * transaction. Also if the response code is 300 or above, which indicates
 * that the transaction has not been successful.
 */
private void performUpload(InputStream in, URL url) throws IOException {
    HttpClient httpClient = null;
    try {
        httpClient = getHttpClient();
        HttpPut httpPut = new HttpPut(url.toExternalForm());
        InputStreamEntity reqEntity = new InputStreamEntity(in, -1);
        reqEntity.setChunked(true);
        httpPut.setEntity(reqEntity);
        HttpResponse response = httpClient.execute(httpPut);

        // HTTP code >= 300 means error!
        if (response.getStatusLine().getStatusCode() >= HTTP_ERROR_CODE_BARRIER) {
            throw new IOException("Could not upload file to URL '" + url.toExternalForm()
                    + "'. got status code '" + response.getStatusLine() + "'");
        }
        log.debug("Uploaded datastream to url '" + url.toString() + "' and " + "received the response line '"
                + response.getStatusLine() + "'.");
    } finally {
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
        }
    }
}

From source file:at.ac.tuwien.dsg.mlr.util.RestfulWSClient.java

public int callPutMethodRC(String xmlString) {
    int statusCode = 0;

    try {// w ww  .  j  av  a2  s  .co  m

        //HttpGet method = new HttpGet(url);
        StringEntity inputKeyspace = new StringEntity(xmlString);

        Logger.getLogger(RestfulWSClient.class.getName()).log(Level.INFO, "Connection .. " + url);

        HttpPut request = new HttpPut(url);
        request.addHeader("content-type", "application/xml; charset=utf-8");
        request.addHeader("Accept", "application/xml, multipart/related");
        request.setEntity(inputKeyspace);

        HttpResponse methodResponse = this.getHttpClient().execute(request);

        statusCode = methodResponse.getStatusLine().getStatusCode();

        Logger.getLogger(RestfulWSClient.class.getName()).log(Level.INFO, "Status Code: " + statusCode);

        // System.out.println("Response String: " + result.toString());
    } catch (Exception ex) {

    }
    return statusCode;
}

From source file:at.ac.tuwien.dsg.depic.dataassetfunctionmanagement.util.TavernaRestAPI.java

public String callPutMethod(String xmlString) {
    String rs = "";

    try {/*from   w w w.  j a v a2 s.co  m*/

        //HttpGet method = new HttpGet(url);
        StringEntity inputKeyspace = new StringEntity(xmlString);

        Logger.getLogger(TavernaRestAPI.class.getName()).log(Level.INFO, "Connection .. " + url);

        HttpPut request = new HttpPut(url);
        request.addHeader("content-type", "application/xml; charset=utf-8");
        //   request.addHeader("Accept", "application/xml, multipart/related");
        request.setEntity(inputKeyspace);

        HttpResponse methodResponse = this.getHttpClient().execute(request);

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

        Logger.getLogger(TavernaRestAPI.class.getName()).log(Level.INFO, "Status Code: " + statusCode);
        BufferedReader rd = new BufferedReader(new InputStreamReader(methodResponse.getEntity().getContent()));

        StringBuilder result = new StringBuilder();
        String line;
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }

        rs = result.toString();
        // System.out.println("Response String: " + result.toString());
    } catch (Exception ex) {

    }
    return rs;
}

From source file:org.gradle.caching.http.internal.HttpBuildCacheService.java

@Override
public void store(BuildCacheKey key, final BuildCacheEntryWriter output) throws BuildCacheException {
    final URI uri = root.resolve(key.getHashCode());
    HttpPut httpPut = new HttpPut(uri);
    httpPut.addHeader(HttpHeaders.CONTENT_TYPE, BUILD_CACHE_CONTENT_TYPE);
    addDiagnosticHeaders(httpPut);/*from ww w. ja va 2s .  co  m*/

    httpPut.setEntity(new AbstractHttpEntity() {
        @Override
        public boolean isRepeatable() {
            return false;
        }

        @Override
        public long getContentLength() {
            return output.getSize();
        }

        @Override
        public InputStream getContent() throws IOException, UnsupportedOperationException {
            throw new UnsupportedOperationException();
        }

        @Override
        public void writeTo(OutputStream outstream) throws IOException {
            output.writeTo(outstream);
        }

        @Override
        public boolean isStreaming() {
            return false;
        }
    });
    CloseableHttpResponse response = null;
    try {
        response = httpClientHelper.performHttpRequest(httpPut);
        StatusLine statusLine = response.getStatusLine();
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Response for PUT {}: {}", safeUri(uri), statusLine);
        }
        int statusCode = statusLine.getStatusCode();
        if (!isHttpSuccess(statusCode)) {
            String defaultMessage = String.format("Storing entry at '%s' response status %d: %s", safeUri(uri),
                    statusCode, statusLine.getReasonPhrase());
            if (isRedirect(statusCode)) {
                handleRedirect(uri, response, statusCode, defaultMessage, "storing entry at");
            } else {
                throwHttpStatusCodeException(statusCode, defaultMessage);
            }
        }
    } catch (ClientProtocolException e) {
        Throwable cause = e.getCause();
        if (cause instanceof NonRepeatableRequestException) {
            throw wrap(cause.getCause());
        } else {
            throw wrap(cause);
        }
    } catch (IOException e) {
        throw wrap(e);
    } finally {
        HttpClientUtils.closeQuietly(response);
    }
}