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.intel.iotkitlib.http.HttpPutTask.java

public CloudResponse doSync(final String url) {
    HttpClient httpClient = new DefaultHttpClient();
    try {/*w  w w  . j a  va2s.c om*/
        HttpContext localContext = new BasicHttpContext();
        HttpPut httpPut = new HttpPut(url);

        if (httpBody != null) {
            //setting HTTP body in entity
            StringEntity bodyEntity = new StringEntity(httpBody, "UTF-8");
            httpPut.setEntity(bodyEntity);
        }

        //adding headers one by one
        for (NameValuePair nvp : headerList) {
            httpPut.addHeader(nvp.getName(), nvp.getValue());
        }

        if (debug) {
            Log.e(TAG, "URI is : " + httpPut.getURI());
            Header[] headers = httpPut.getAllHeaders();
            for (int i = 0; i < headers.length; i++) {
                Log.e(TAG, "Header " + i + " is :" + headers[i].getName() + ":" + headers[i].getValue());
            }
            if (httpBody != null) {
                BufferedReader reader123 = new BufferedReader(
                        new InputStreamReader(httpPut.getEntity().getContent(), HTTP.UTF_8));
                StringBuilder builder123 = new StringBuilder();
                for (String line = null; (line = reader123.readLine()) != null;) {
                    builder123.append(line).append("\n");
                }
                Log.e(TAG, "Body is :" + builder123.toString());
            }
        }

        HttpResponse response = httpClient.execute(httpPut, localContext);
        if (response != null && response.getStatusLine() != null) {
            if (debug)
                Log.d(TAG, "response: " + response.getStatusLine().getStatusCode());
        }

        HttpEntity responseEntity = response != null ? response.getEntity() : null;
        StringBuilder builder = new StringBuilder();
        if (responseEntity != null) {
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(responseEntity.getContent(), HTTP.UTF_8));
            for (String line = null; (line = reader.readLine()) != null;) {
                builder.append(line).append("\n");
            }
            if (debug)
                Log.d(TAG, "Response received is :" + builder.toString());
        }

        CloudResponse cloudResponse = new CloudResponse();
        if (response != null) {
            cloudResponse.code = response.getStatusLine().getStatusCode();
        }
        cloudResponse.response = builder.toString();
        return cloudResponse;
    } catch (java.net.ConnectException cEx) {
        Log.e(TAG, cEx.getMessage());
        return new CloudResponse(false, cEx.getMessage());
    } catch (Exception e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
        return new CloudResponse(false, e.getMessage());
    }
}

From source file:org.fusesource.fabric.itests.paxexam.FabricMavenProxyTest.java

@Test
public void testUpload() throws Exception {
    String featureLocation = System.getProperty("feature.location");
    System.out.println("Testing with feature from:" + featureLocation);
    System.err.println(executeCommand("fabric:create -n"));
    Set<Container> containers = ContainerBuilder.create(2).withName("maven").withProfiles("fabric")
            .assertProvisioningResult().build();

    FabricService fabricService = getFabricService();
    CuratorFramework curator = getCurator();
    List<String> children = getChildren(curator, ZkPath.MAVEN_PROXY.getPath("upload"));
    List<String> uploadUrls = new ArrayList<String>();
    for (String child : children) {
        String uploadeUrl = getSubstitutedPath(curator, ZkPath.MAVEN_PROXY.getPath("upload") + "/" + child);
        uploadUrls.add(uploadeUrl);/*  w w w . j  ava  2s  .c  o m*/
    }
    //Pick a random maven proxy from the list.
    Random random = new Random();
    int index = random.nextInt(uploadUrls.size());
    String targetUrl = uploadUrls.get(index);

    String uploadUrl = targetUrl + "itest/itest/1.0/itest-1.0-features.xml";
    System.out.println("Using URI: " + uploadUrl);
    DefaultHttpClient client = new DefaultHttpClient();
    HttpPut put = new HttpPut(uploadUrl);
    client.getCredentialsProvider().setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials("admin", "admin"));

    FileNIOEntity entity = new FileNIOEntity(new File(featureLocation), "text/xml");
    put.setEntity(entity);
    HttpResponse response = client.execute(put);
    System.err.println("Response:" + response.getStatusLine());
    Assert.assertTrue(
            response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 202);

    System.err.println(
            executeCommand("fabric:profile-edit --repositories mvn:itest/itest/1.0/xml/features default"));
    System.err.println(executeCommand("fabric:profile-edit --features example-cbr default"));
    Provision.waitForContainerStatus(containers, PROVISION_TIMEOUT);
}

From source file:org.caratarse.auth.services.controller.UserControllerTest.java

@Test
public void updateUser() throws IOException {
    HttpPut putRequest = new HttpPut(BASE_URL + "/users/a1ab82a6-c8ce-4723-8532-777c4b05d03c");
    StringEntity input = new StringEntity("{\"username\":\"updUsername\",\"password\":\"updPwd\"}");
    input.setContentType("application/json");
    putRequest.setEntity(input);
    HttpResponse response = httpClient.execute(putRequest);
    assertEquals(204, response.getStatusLine().getStatusCode());
    HttpGet getRequest = new HttpGet(BASE_URL + "/users/a1ab82a6-c8ce-4723-8532-777c4b05d03c.json");
    response = httpClient.execute(getRequest);
    assertEquals(200, response.getStatusLine().getStatusCode());
    log.debug(IOUtils.toString(response.getEntity().getContent()));
}

From source file:org.fusesource.fabric.itests.smoke.FabricMavenProxyTest.java

@Test
public void testUpload() throws Exception {
    String featureLocation = System.getProperty("feature.location");
    System.out.println("Testing with feature from:" + featureLocation);
    System.err.println(executeCommand("fabric:create -n"));
    Set<Container> containers = ContainerBuilder.create(2).withName("maven").withProfiles("fabric")
            .assertProvisioningResult().build();

    FabricService fabricService = getFabricService();
    CuratorFramework curator = getCurator();
    List<String> children = getChildren(curator, ZkPath.MAVEN_PROXY.getPath("upload"));
    List<String> uploadUrls = new ArrayList<String>();
    for (String child : children) {
        String uploadeUrl = getSubstitutedPath(curator, ZkPath.MAVEN_PROXY.getPath("upload") + "/" + child);
        uploadUrls.add(uploadeUrl);//ww  w.  jav a 2  s . c o m
    }
    //Pick a random maven proxy from the list.
    Random random = new Random();
    int index = random.nextInt(uploadUrls.size());
    String targetUrl = uploadUrls.get(index);

    String uploadUrl = targetUrl + "itest/itest/1.0/itest-1.0-features.xml";
    System.out.println("Using URI: " + uploadUrl);
    DefaultHttpClient client = new DefaultHttpClient();
    HttpPut put = new HttpPut(uploadUrl);
    client.getCredentialsProvider().setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials("admin", "admin"));

    FileNIOEntity entity = new FileNIOEntity(new File(featureLocation), "text/xml");
    put.setEntity(entity);
    HttpResponse response = client.execute(put);
    System.err.println("Response:" + response.getStatusLine());
    Assert.assertTrue(
            response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 202);

    System.err.println(
            executeCommand("fabric:profile-edit --repositories mvn:itest/itest/1.0/xml/features default"));
    System.err.println(executeCommand("fabric:profile-edit --features example-cbr default"));
    Provision.containerStatus(containers, PROVISION_TIMEOUT);
}

From source file:org.apache.hadoop.gateway.dispatch.DefaultDispatch.java

@Override
public void doPut(URI url, HttpServletRequest request, HttpServletResponse response)
        throws IOException, URISyntaxException {
    HttpPut method = new HttpPut(url);
    HttpEntity entity = createRequestEntity(request);
    method.setEntity(entity);
    copyRequestHeaderFields(method, request);
    executeRequest(method, request, response);
}

From source file:org.commonjava.util.jhttpc.it.AbstractIT.java

protected void putContent(String path, String content) throws Exception {
    String url = formatUrl(CONTENT_MGMT_PATH, path);
    HttpPut put = new HttpPut(url);
    put.setEntity(new StringEntity(content));

    CloseableHttpClient client = null;/*from ww w .  ja v  a  2  s.c om*/
    try {
        client = factory.createClient();
        CloseableHttpResponse response = client.execute(put);
        int code = response.getStatusLine().getStatusCode();
        if (code != 200 && code != 201) {
            String extra = "";
            if (response.getEntity() != null) {
                String body = IOUtils.toString(response.getEntity().getContent());
                extra = "\nBody:\n\n" + body;
            }

            Assert.fail("Failed to put content to: " + path + ".\nURL: " + url + "\nStatus: "
                    + response.getStatusLine() + extra);
        }
    } finally {
        IOUtils.closeQuietly(client);
    }
}

From source file:com.foundationdb.http.CsrfProtectionITBase.java

@Test
public void putAllowed() throws Exception {
    HttpPut request = new HttpPut(defaultURI("/1"));
    request.setHeader("Referer", "http://somewhere.com");
    request.setHeader("Content-Type", "application/json");
    request.setEntity(new StringEntity("{\"id\": \"1\"}"));

    response = client.execute(request);//from  ww  w  . j a va  2s.c o  m
    assertEquals("status", HttpStatus.SC_OK, response.getStatusLine().getStatusCode());
}

From source file:at.ac.tuwien.dsg.elasticdaasclient.testing.RestfulWSClient.java

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

    try {//from  ww w  . j  a v a  2 s .  c  om

        //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);

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

        Logger.getLogger(RestfulWSClient.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:io.liveoak.pgsql.BasePgSqlHttpTest.java

protected String putRequest(HttpPut put, String json) throws IOException {

    StringEntity entity = new StringEntity(json, ContentType.create(APPLICATION_JSON, "UTF-8"));
    put.setEntity(entity);

    System.err.println("DO PUT - " + put.getURI());
    System.out.println("\n" + json);

    CloseableHttpResponse result = httpClient.execute(put);

    System.err.println("=============>>>");
    System.err.println(result);//from   w w w  . j a  v  a2s  .  c  om

    HttpEntity resultEntity = result.getEntity();

    assertThat(resultEntity.getContentLength()).isGreaterThan(0);

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    resultEntity.writeTo(baos);

    String resultStr = new String(baos.toByteArray());
    System.err.println(resultStr);
    System.err.println("\n<<<=============");
    return resultStr;
}