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.clarionmedia.infinitum.http.rest.impl.CachingEnabledRestfulClient.java

@Override
public RestResponse executePut(String uri, InputStream messageBody, int messageBodyLength, String contentType) {
    HttpPut httpPut = new HttpPut(uri);
    httpPut.addHeader("content-type", contentType);
    httpPut.setEntity(new InputStreamEntity(messageBody, messageBodyLength));
    try {// www . j  a  v a2  s. c om
        RequestWrapper request = new RequestWrapper(httpPut);
        return executeRequest(new HashableHttpRequest(request));
    } catch (ProtocolException e) {
        throw new InfinitumRuntimeException("Unable to execute request", e);
    }
}

From source file:com.impetus.kundera.ycsb.benchmark.CouchDBNativeClient.java

@Override
public int insert(String table, String key, HashMap<String, ByteIterator> values) {
    HttpResponse response = null;/*  w w w . j  a v  a2  s.c o  m*/
    try {
        System.out.println("Inserting ....");
        JsonObject object = new JsonObject();
        for (Map.Entry<String, ByteIterator> entry : values.entrySet()) {
            object.addProperty(entry.getKey(), entry.getValue().toString());
        }
        URI uri = new URI(CouchDBConstants.PROTOCOL, null, httpHost.getHostName(), httpHost.getPort(),
                CouchDBConstants.URL_SAPRATOR + database.toLowerCase() + CouchDBConstants.URL_SAPRATOR + table
                        + key,
                null, null);

        HttpPut put = new HttpPut(uri);

        StringEntity stringEntity = null;
        object.addProperty("_id", table + key);
        stringEntity = new StringEntity(object.toString(), Constants.CHARSET_UTF8);
        stringEntity.setContentType("application/json");
        put.setEntity(stringEntity);

        response = httpClient.execute(httpHost, put, CouchDBUtils.getContext(httpHost));

        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_NOT_FOUND) {
            return 1;
        }
        return 0;
    } catch (Exception e) {
        throw new RuntimeException(e);
    } finally {
        // CouchDBUtils.closeContent(response);
    }
}

From source file:com.mondora.chargify.controller.HttpsXmlChargify.java

/**
 * {@inheritDoc}/*from  w  ww . j  a  va2s.c o m*/
 */
@Override
public void updateCustomer(Customer customer) {
    log.debug("updateCustomer() customer:{}", customer);
    try {
        HttpPut customersHttpPost = new HttpPut(base + "/customers/" + customer.getId() + ".xml");
        customersHttpPost.setEntity(marshal(customer));
        HttpResponse response = httpClient.execute(customersHttpPost);
        StreamSource streamSource = createStreamSource(response);
        throwExceptionIfNeeded(response.getStatusLine(), streamSource);
    } catch (IOException e) {
        log.error("updateCustomer() caught exception", e);
        throw new RuntimeException(e);
    } catch (IllegalStateException e) {
        log.error("updateCustomer() caught exception", e);
        throw new RuntimeException(e);
    }
}

From source file:com.talis.platform.testsupport.StubHttpTest.java

@Test
public void expectedOnePutReturning200WithBadData() throws Exception {
    stubHttp.expect("PUT", "/my/path").withEntity("mydata").andReturn(200, "My data...");
    stubHttp.replay();/*  w  ww. j  a  v  a2s  .  co m*/

    HttpPut put = new HttpPut(stubHttp.getBaseUrl() + "/my/path");
    put.setEntity(new StringEntity("not_my_data"));
    assertExpectedStatusAndEntity("", 500, put);

    assertTestFailureWithErrorPrefix("Stub server did not get correct set of calls");
}

From source file:com.cloudbees.gasp.service.RESTService.java

@Override
protected void onHandleIntent(Intent intent) {
    // When an intent is received by this Service, this method
    // is called on a new thread.

    Uri action = intent.getData();//from ww  w.  j ava2 s  .com
    Bundle extras = intent.getExtras();

    if (extras == null || action == null || !extras.containsKey(EXTRA_RESULT_RECEIVER)) {
        // Extras contain our ResultReceiver and data is our REST action.  
        // So, without these components we can't do anything useful.
        Log.e(TAG, "You did not pass extras or data with the Intent.");

        return;
    }

    // We default to GET if no verb was specified.
    int verb = extras.getInt(EXTRA_HTTP_VERB, GET);
    Bundle params = extras.getParcelable(EXTRA_PARAMS);
    ResultReceiver receiver = extras.getParcelable(EXTRA_RESULT_RECEIVER);

    try {
        // Here we define our base request object which we will
        // send to our REST service via HttpClient.
        HttpRequestBase request = null;

        // Let's build our request based on the HTTP verb we were
        // given.
        switch (verb) {
        case GET: {
            request = new HttpGet();
            attachUriWithQuery(request, action, params);
        }
            break;

        case DELETE: {
            request = new HttpDelete();
            attachUriWithQuery(request, action, params);
        }
            break;

        case POST: {
            request = new HttpPost();
            request.setURI(new URI(action.toString()));

            // Attach form entity if necessary. Note: some REST APIs
            // require you to POST JSON. This is easy to do, simply use
            // postRequest.setHeader('Content-Type', 'application/json')
            // and StringEntity instead. Same thing for the PUT case 
            // below.
            HttpPost postRequest = (HttpPost) request;

            if (params != null) {
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramsToList(params));
                postRequest.setEntity(formEntity);
            }
        }
            break;

        case PUT: {
            request = new HttpPut();
            request.setURI(new URI(action.toString()));

            // Attach form entity if necessary.
            HttpPut putRequest = (HttpPut) request;

            if (params != null) {
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramsToList(params));
                putRequest.setEntity(formEntity);
            }
        }
            break;
        }

        if (request != null) {
            HttpClient client = new DefaultHttpClient();

            // Let's send some useful debug information so we can monitor things
            // in LogCat.
            Log.d(TAG, "Executing request: " + verbToString(verb) + ": " + action.toString());

            // Finally, we send our request using HTTP. This is the synchronous
            // long operation that we need to run on this thread.
            HttpResponse response = client.execute(request);

            HttpEntity responseEntity = response.getEntity();
            StatusLine responseStatus = response.getStatusLine();
            int statusCode = responseStatus != null ? responseStatus.getStatusCode() : 0;

            // Our ResultReceiver allows us to communicate back the results to the caller. This
            // class has a method named send() that can send back a code and a Bundle
            // of data. ResultReceiver and IntentService abstract away all the IPC code
            // we would need to write to normally make this work.
            if (responseEntity != null) {
                Bundle resultData = new Bundle();
                resultData.putString(REST_RESULT, EntityUtils.toString(responseEntity));
                receiver.send(statusCode, resultData);
            } else {
                receiver.send(statusCode, null);
            }
        }
    } catch (URISyntaxException e) {
        Log.e(TAG, "URI syntax was incorrect. " + verbToString(verb) + ": " + action.toString(), e);
        receiver.send(0, null);
    } catch (UnsupportedEncodingException e) {
        Log.e(TAG, "A UrlEncodedFormEntity was created with an unsupported encoding.", e);
        receiver.send(0, null);
    } catch (ClientProtocolException e) {
        Log.e(TAG, "There was a problem when sending the request.", e);
        receiver.send(0, null);
    } catch (IOException e) {
        Log.e(TAG, "There was a problem when sending the request.", e);
        receiver.send(0, null);
    }
}

From source file:com.talis.platform.testsupport.StubHttpTest.java

@Test
public void expectedOnePutReturning200WithCorrectData() throws Exception {
    String expectedEntity = "My data...";
    stubHttp.expect("PUT", "/my/path").withEntity("mydata").andReturn(200, expectedEntity);
    stubHttp.replay();/*from www . j a  v  a 2 s  . c o  m*/

    HttpPut put = new HttpPut(stubHttp.getBaseUrl() + "/my/path");
    put.setEntity(new StringEntity("mydata"));
    assertExpectedStatusAndEntity(expectedEntity, 200, put);

    stubHttp.verify();
}

From source file:com.talis.platform.testsupport.StubHttpTest.java

@Test
public void expectedOnePutReturning200WithCorrectDataAndContentType() throws Exception {
    String expectedEntity = "My data...";
    stubHttp.expect("PUT", "/my/path").withEntity("mydata").withHeader("Content-Type", "text/turtle")
            .andReturn(200, expectedEntity);
    stubHttp.replay();/*  ww  w .java 2  s .  c  o m*/

    HttpPut put = new HttpPut(stubHttp.getBaseUrl() + "/my/path");
    put.setEntity(new StringEntity("mydata"));
    put.setHeader(HttpHeaders.CONTENT_TYPE, "text/turtle");
    assertExpectedStatusAndEntity(expectedEntity, 200, put);

    stubHttp.verify();
}

From source file:com.talis.platform.testsupport.StubHttpTest.java

@Test
public void expectedOnePutReturning200WithCorrectDataAndBadContentType() throws Exception {
    String expectedEntity = "My data...";
    stubHttp.expect("PUT", "/my/path").withEntity("mydata").withHeader(HttpHeaders.CONTENT_TYPE, "text/turtle")
            .andReturn(200, expectedEntity);
    stubHttp.replay();//from w  w w  . java 2  s  .c om

    HttpPut put = new HttpPut(stubHttp.getBaseUrl() + "/my/path");
    put.setEntity(new StringEntity("mydata"));
    put.setHeader(HttpHeaders.CONTENT_TYPE, "application/json");
    assertExpectedStatusAndEntity("", 500, put);

    assertTestFailureWithErrorPrefix("Stub server did not get correct set of calls");
}

From source file:com.appjma.appdeployer.service.Downloader.java

private void updateApp(String token, String id, String guid, String name) throws ClientProtocolException,
        IOException, UnauthorizedResponseCode, WrongHttpResponseCode, JSONException {
    String url = new GetBuilder(BASE_API_URL).appendPathSegment("apps").appendPathSegment(guid).build();
    HttpPut request = new HttpPut(url);
    try {//  w w  w  .  jav  a2 s . c o  m
        JSONObject obj = new JSONObject();
        obj.put("name", name);
        request.setEntity(getJsonEntity(obj));
    } catch (JSONException e) {
        throw new RuntimeException(e);
    }
    setupDefaultHeaders(request, token);
    HttpResponse response = getHttpClient().execute(request);
    int statusCode = response.getStatusLine().getStatusCode();
    if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
        throw new UnauthorizedResponseCode(response, token);
    }
    if (statusCode != HttpStatus.SC_OK) {
        throw new WrongHttpResponseCode(response);
    }
    JSONObject json = HTTPUtils.getJsonFromResponse(response);
    try {
        mParser.parseApp(id, json);
        mParserResult.apply();
    } finally {
        mParserResult.clear();
    }
}

From source file:riddimon.android.asianetautologin.HttpUtils.java

private HttpResponse execute(HttpMethod method, String url, Map<String, String> paramz,
        List<BasicHeader> headers) {
    if (!(method.equals(HttpMethod.GET) || method.equals(HttpMethod.DELETE) || method.equals(HttpMethod.PUT)
            || method.equals(HttpMethod.POST) || method.equals(HttpMethod.HEAD)) || TextUtils.isEmpty(url)) {
        logger.error("Invalid request : {} | {}", method.name(), url);
        return null;
    }/*from  w w  w . j  av a2s. co m*/
    logger.debug("HTTP {} : {}", method.name(), url);
    String query = paramz == null ? null : getEncodedParameters(paramz);
    logger.trace("Query String : {}", query);
    HttpResponse httpResponse = null;
    try {
        HttpUriRequest req = null;
        switch (method) {
        case GET:
        case HEAD:
        case DELETE:
            url = paramz != null && paramz.size() > 0 ? url + "?" + query : url;
            if (method.equals(HttpMethod.GET)) {
                req = new HttpGet(url);
            } else if (method.equals(HttpMethod.DELETE)) {
                req = new HttpDelete(url);
            } else if (method.equals(HttpMethod.HEAD)) {
                req = new HttpHead(url);
            }
            break;
        case POST:
        case PUT:
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            if (paramz != null) {
                for (Entry<String, String> entry : paramz.entrySet()) {
                    params.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
            }
            UrlEncodedFormEntity entity = paramz == null ? null : new UrlEncodedFormEntity(params);
            //               HttpEntity entity = TextUtils.isEmpty(query) ? null
            //                     : new StringEntity(query);
            BasicHeader header = new BasicHeader(HTTP.CONTENT_ENCODING, "application/x-www-form-urlencoded");
            if (method.equals(HttpMethod.PUT)) {
                HttpPut putr = new HttpPut(url);
                if (entity != null) {
                    putr.setHeader(header);
                    putr.setEntity(entity);
                    req = putr;
                }
            } else if (method.equals(HttpMethod.POST)) {
                HttpPost postr = new HttpPost(url);
                if (entity != null) {
                    postr.setHeader(header);
                    if (headers != null) {
                        for (BasicHeader h : headers) {
                            postr.addHeader(h);
                        }
                    }
                    postr.setEntity(entity);
                    req = postr;
                }
            }
        }
        httpResponse = HttpManager.execute(req, debug, version);
    } catch (IOException e1) {
        e1.printStackTrace();
        logger.error("HTTP request failed : {}", e1);
    }
    return httpResponse;
}