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.hoccer.api.RESTfulApiTest.java

private void publishPosition(String uri)
        throws UnsupportedEncodingException, IOException, ClientProtocolException {
    HttpPut envUpdate = new HttpPut(
            ApiSigningTools.sign(uri, ApiKeySigningTest.demoKey, ApiKeySigningTest.demoSecret));
    envUpdate.setEntity(new StringEntity(
            "{\"gps\": {\"longitude\": " + latitude++ + ", \"latitude\": 50, \"accuracy\": 100} }"));
    HttpResponse response = mHttpClient.execute(envUpdate);
    assertEquals(/*from w w  w  . j  a  v a 2 s. c  o m*/
            "should have updated the environment but server said " + EntityUtils.toString(response.getEntity()),
            201, response.getStatusLine().getStatusCode());
    envUpdate.abort();
}

From source file:org.fcrepo.oai.integration.AbstractOAIProviderIT.java

protected void createBinaryObject(final String binaryId, final InputStream src) throws IOException {
    final HttpPut put = new HttpPut(serverAddress + "/" + binaryId);
    put.setEntity(new StringEntity(IOUtils.toString(src)));
    final HttpResponse resp = this.client.execute(put);
    assertEquals(201, resp.getStatusLine().getStatusCode());
    put.releaseConnection();/*from   w w  w  . j  ava2s  .co m*/
}

From source file:com.decody.android.core.json.JSONClient.java

public <T> T put(String url, Class<T> classOfT, T data)
        throws ResourceNotFoundException, UnauthorizedException {
    HttpPut put = new HttpPut(url);
    put.addHeader("Content-Type", CONTENT_TYPE);

    try {//from ww  w .j a va 2  s  .co m
        put.setEntity(new StringEntity(factory.newInstance().toJson(data)));
    } catch (UnsupportedEncodingException e) {
        throw new IllegalArgumentException(
                "input data is not valid, check the input data to call the post service: " + url + " - "
                        + classOfT.toString());
    }

    return performCall(put, classOfT);
}

From source file:com.meplato.store2.ApacheHttpClient.java

/**
 * Execute runs a HTTP request/response with an API endpoint.
 *
 * @param method      the HTTP method, e.g. POST or GET
 * @param uriTemplate the URI template according to RFC 6570
 * @param parameters  the query string parameters
 * @param headers     the key/value pairs for the HTTP header
 * @param body        the body of the request or {@code null}
 * @return the HTTP response encapsulated by {@link Response}.
 * @throws ServiceException if e.g. the service is unavailable.
 *///from w ww  . j ava2 s.  c  o  m
@Override
public Response execute(String method, String uriTemplate, Map<String, Object> parameters,
        Map<String, String> headers, Object body) throws ServiceException {
    // URI template parameters
    String url = UriTemplate.fromTemplate(uriTemplate).expand(parameters);

    // Body
    HttpEntity requestEntity = null;
    if (body != null) {
        Gson gson = getSerializer();
        try {
            requestEntity = EntityBuilder.create().setText(gson.toJson(body)).setContentEncoding("UTF-8")
                    .setContentType(ContentType.APPLICATION_JSON).build();
        } catch (Exception e) {
            throw new ServiceException("Error serializing body", null, e);
        }
    }

    // Do HTTP request
    HttpRequestBase httpRequest = null;
    if (method.equalsIgnoreCase("GET")) {
        httpRequest = new HttpGet(url);
    } else if (method.equalsIgnoreCase("POST")) {
        HttpPost httpPost = new HttpPost(url);
        if (requestEntity != null) {
            httpPost.setEntity(requestEntity);
        }
        httpRequest = httpPost;
    } else if (method.equalsIgnoreCase("PUT")) {
        HttpPut httpPut = new HttpPut(url);
        if (requestEntity != null) {
            httpPut.setEntity(requestEntity);
        }
        httpRequest = httpPut;
    } else if (method.equalsIgnoreCase("DELETE")) {
        httpRequest = new HttpDelete(url);
    } else if (method.equalsIgnoreCase("PATCH")) {
        HttpPatch httpPatch = new HttpPatch(url);
        if (requestEntity != null) {
            httpPatch.setEntity(requestEntity);
        }
        httpRequest = httpPatch;
    } else if (method.equalsIgnoreCase("HEAD")) {
        httpRequest = new HttpHead(url);
    } else if (method.equalsIgnoreCase("OPTIONS")) {
        httpRequest = new HttpOptions(url);
    } else {
        throw new ServiceException("Invalid HTTP method: " + method, null, null);
    }

    // Headers
    for (Map.Entry<String, String> entry : headers.entrySet()) {
        httpRequest.addHeader(entry.getKey(), entry.getValue());
    }
    httpRequest.setHeader("Accept", "application/json");
    httpRequest.setHeader("Accept-Charset", "utf-8");
    httpRequest.setHeader("Content-Type", "application/json; charset=utf-8");
    httpRequest.setHeader("User-Agent", USER_AGENT);

    try (CloseableHttpResponse httpResponse = httpClient.execute(httpRequest)) {
        Response response = new ApacheHttpResponse(httpResponse);
        int statusCode = response.getStatusCode();
        if (statusCode >= 200 && statusCode < 300) {
            return response;
        }
        throw ServiceException.fromResponse(response);
    } catch (ClientProtocolException e) {
        throw new ServiceException("Client Protocol Exception", null, e);
    } catch (IOException e) {
        throw new ServiceException("IO Exception", null, e);
    }
}

From source file:org.codice.alliance.nsili.endpoint.requests.FtpDestinationSink.java

@Override
public void writeFile(InputStream fileData, long size, String name, String contentType,
        List<Metacard> metacards) throws IOException {
    CloseableHttpClient httpClient = null;
    String urlPath = protocol + "://" + fileLocation.host_name + ":" + port + "/" + fileLocation.path_name + "/"
            + name;/*  w  w w .j  a  v  a 2s . co  m*/

    LOGGER.debug("Writing ordered file to URL: {}", urlPath);

    try {
        HttpPut putMethod = new HttpPut(urlPath);
        putMethod.addHeader(HTTP.CONTENT_TYPE, contentType);
        HttpEntity httpEntity = new InputStreamEntity(fileData, size);
        putMethod.setEntity(httpEntity);

        if (StringUtils.isNotEmpty(fileLocation.user_name) && fileLocation.password != null) {
            CredentialsProvider credsProvider = new BasicCredentialsProvider();
            credsProvider.setCredentials(new AuthScope(fileLocation.host_name, port),
                    new UsernamePasswordCredentials(fileLocation.user_name, fileLocation.password));
            httpClient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();
        } else {
            httpClient = HttpClients.createDefault();
        }

        httpClient.execute(putMethod);
        fileData.close();
        putMethod.releaseConnection();
    } finally {
        if (httpClient != null) {
            httpClient.close();
        }
    }
}

From source file:net.sourcewalker.garanbot.api.GaranboClient.java

/**
 * Execute HTTP PUT with URL and provided content.
 * //from ww  w. ja va  2 s  .c o  m
 * @param path
 *            Path to PUT to.
 * @param jsonData
 *            String with content to send.
 * @return HTTP Response return by server.
 * @throws IOException
 *             When there was an error communicating with the server.
 */
public HttpResponse put(String path, String jsonData) throws IOException {
    HttpPut request = new HttpPut(ApiConstants.BASE + path);
    request.setEntity(new StringEntity(jsonData));
    prepareRequest(request);
    return client.execute(request);
}

From source file:nl.gridline.zieook.workflow.rest.CollectionImportCompleteTest.java

@Ignore
private int collectionUpload(String url, File file) {
    // upload binary collection data

    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpEntity entity = new FileEntity(file, "binary/octet-stream");

    HttpPut post = new HttpPut(url);
    post.setEntity(entity);
    try {//from w ww  .  ja  va  2 s  .c o m
        HttpResponse response = httpclient.execute(post);
        return response.getStatusLine().getStatusCode();
    } catch (ClientProtocolException e) {
        LOG.error("upload failed", e);
        fail("upload failed");
    } catch (IOException e) {
        LOG.error("upload failed", e);
        fail("upload failed");
    }
    return 500;
}

From source file:net.sourcewalker.garanbot.api.GaranboClient.java

/**
 * Execute HTTP PUT with URL and provided content.
 * /*  ww  w .j a v a  2s  .  c o  m*/
 * @param path
 *            Path to PUT to.
 * @param contentType
 *            MIMEtype of content.
 * @param stream
 *            Stream with data to send to server.
 * @param streamSize
 *            Length of data.
 * @return HTTP Response return by server.
 * @throws IOException
 *             When there was an error communicating with the server.
 */
public HttpResponse put(final String path, final String contentType, final InputStream stream,
        final long streamSize) throws IOException {
    HttpPut request = new HttpPut(ApiConstants.BASE + path);
    request.setEntity(new InputStreamEntity(stream, streamSize));
    prepareRequest(contentType, request);
    return client.execute(request);
}

From source file:io.undertow.js.test.jdbc.JavascriptJDBCWrapperTestCase.java

@Test
public void testDatabaseCRUDOperations() throws IOException, ScriptException {
    final TestHttpClient client = new TestHttpClient();
    try {//from  ww w .  j  a v a 2  s .  co  m
        HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/customers");
        post.setEntity(new StringEntity("{\"first\": \"John\", \"last\": \"Doe\"}"));
        HttpResponse result = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        Assert.assertEquals("1", HttpClientUtils.readResponse(result));

        HttpGet get = new HttpGet(DefaultServer.getDefaultServerURL() + "/customers");
        result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        String json = HttpClientUtils.readResponse(result);

        Assert.assertEquals("John", js.evaluate("JSON.parse('" + json + "')[0].FIRST"));
        Assert.assertEquals("Doe", js.evaluate("JSON.parse('" + json + "')[0].LAST"));
        String id = js.evaluate("JSON.parse('" + json + "')[0].ID").toString();
        Assert.assertNotNull(id);

        get = new HttpGet(DefaultServer.getDefaultServerURL() + "/customers/" + id);
        result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        json = HttpClientUtils.readResponse(result);

        Assert.assertEquals("John", js.evaluate("JSON.parse('" + json + "').FIRST"));
        Assert.assertEquals("Doe", js.evaluate("JSON.parse('" + json + "').LAST"));
        id = js.evaluate("JSON.parse('" + json + "').ID").toString();
        Assert.assertNotNull(id);

        HttpPut put = new HttpPut(DefaultServer.getDefaultServerURL() + "/customers/" + id);
        put.setEntity(new StringEntity("{\"first\": \"John\", \"last\": \"Smith\"}"));
        result = client.execute(put);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        Assert.assertEquals("1", HttpClientUtils.readResponse(result));

        get = new HttpGet(DefaultServer.getDefaultServerURL() + "/customers/" + id);
        result = client.execute(get);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        json = HttpClientUtils.readResponse(result);

        Assert.assertEquals("John", js.evaluate("JSON.parse('" + json + "').FIRST"));
        Assert.assertEquals("Smith", js.evaluate("JSON.parse('" + json + "').LAST"));
        id = js.evaluate("JSON.parse('" + json + "').ID").toString();
        Assert.assertNotNull(id);

        HttpDelete delete = new HttpDelete(DefaultServer.getDefaultServerURL() + "/customers/" + id);
        result = client.execute(delete);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        Assert.assertEquals("1", HttpClientUtils.readResponse(result));

        get = new HttpGet(DefaultServer.getDefaultServerURL() + "/customers/" + id);
        result = client.execute(get);
        Assert.assertEquals(StatusCodes.NOT_FOUND, result.getStatusLine().getStatusCode());
        json = HttpClientUtils.readResponse(result);
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:org.talend.librariesmanager.maven.ArtifactsDeployer.java

private void installToRemote(HttpEntity entity, URL targetURL) throws Exception {
    DefaultHttpClient httpClient = new DefaultHttpClient();
    try {/*  ww  w  .  j av  a2  s .c o m*/
        httpClient.getCredentialsProvider().setCredentials(
                new AuthScope(targetURL.getHost(), targetURL.getPort()),
                new UsernamePasswordCredentials(nexusServer.getUserName(), nexusServer.getPassword()));

        HttpPut httpPut = new HttpPut(targetURL.toString());
        httpPut.setEntity(entity);
        HttpResponse response = httpClient.execute(httpPut);
        StatusLine statusLine = response.getStatusLine();
        int responseCode = statusLine.getStatusCode();
        EntityUtils.consume(entity);
        if (responseCode > 399) {
            if (responseCode == 500) {
                // ignor this error , if .pom already exist on server and deploy again will get this error
            } else if (responseCode == 401) {
                throw new BusinessException("Authrity failed");
            } else {
                throw new BusinessException(
                        "Deploy failed: " + responseCode + ' ' + statusLine.getReasonPhrase());
            }
        }
    } catch (Exception e) {
        throw new Exception(targetURL.toString(), e);
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}