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.appdynamics.demo.gasp.service.RESTIntentService.java

@Override
protected void onHandleIntent(Intent intent) {
    Uri action = intent.getData();//from w w  w .ja v a 2s .  co  m
    Bundle extras = intent.getExtras();

    if (extras == null || action == null || !extras.containsKey(EXTRA_RESULT_RECEIVER)) {
        Log.e(TAG, "You did not pass extras or data with the Intent.");
        return;
    }

    int verb = extras.getInt(EXTRA_HTTP_VERB, GET);
    Bundle params = extras.getParcelable(EXTRA_PARAMS);
    Bundle headers = extras.getParcelable(EXTRA_HEADERS);
    ResultReceiver receiver = extras.getParcelable(EXTRA_RESULT_RECEIVER);

    try {
        HttpRequestBase request = null;

        // Get query params from Bundle and build URL
        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()));

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

            HttpPut putRequest = (HttpPut) request;

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

        // Get Headers from Bundle
        for (BasicNameValuePair header : paramsToList(headers)) {
            request.setHeader(header.getName(), header.getValue());
        }

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

            Log.d(TAG, "Executing request: " + verbToString(verb) + ": " + action.toString());

            HttpResponse response = client.execute(request);

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

            if ((responseEntity != null) && (responseStatus.getStatusCode() == 200)) {
                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);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.urbancode.ud.client.EnvironmentClient.java

public void createDesiredInventoryEntry(String deploymentRequest, String environmentId, String componentId,
        String versionId, String status) throws IOException, JSONException {
    String uri = url + "/rest/inventory/desiredInventory/entries";

    JSONObject entry = new JSONObject();
    entry.put("environmentId", environmentId);
    entry.put("componentId", componentId);
    entry.put("versionId", versionId);
    entry.put("status", status);

    JSONArray entries = new JSONArray();
    entries.put(entry);/*  ww w. j a v  a  2s.  c o m*/

    JSONObject requestBody = new JSONObject();
    requestBody.put("deploymentRequest", deploymentRequest);
    requestBody.put("entries", entries);

    HttpPut method = new HttpPut(uri);
    try {
        method.setEntity(getStringEntity(requestBody));
        invokeMethod(method);
    } finally {
        releaseConnection(method);
    }
}

From source file:org.springframework.cloud.netflix.zuul.filters.route.SimpleHostRoutingFilter.java

protected HttpRequest buildHttpRequest(String verb, String uri, InputStreamEntity entity,
        MultiValueMap<String, String> headers, MultiValueMap<String, String> params) {
    HttpRequest httpRequest;/* w  w  w .j  ava2s.  c o  m*/

    switch (verb.toUpperCase()) {
    case "POST":
        HttpPost httpPost = new HttpPost(uri + this.helper.getQueryString(params));
        httpRequest = httpPost;
        httpPost.setEntity(entity);
        break;
    case "PUT":
        HttpPut httpPut = new HttpPut(uri + this.helper.getQueryString(params));
        httpRequest = httpPut;
        httpPut.setEntity(entity);
        break;
    case "PATCH":
        HttpPatch httpPatch = new HttpPatch(uri + this.helper.getQueryString(params));
        httpRequest = httpPatch;
        httpPatch.setEntity(entity);
        break;
    case "DELETE":
        BasicHttpEntityEnclosingRequest entityRequest = new BasicHttpEntityEnclosingRequest(verb,
                uri + this.helper.getQueryString(params));
        httpRequest = entityRequest;
        entityRequest.setEntity(entity);
        break;
    default:
        httpRequest = new BasicHttpRequest(verb, uri + this.helper.getQueryString(params));
        log.debug(uri + this.helper.getQueryString(params));
    }

    httpRequest.setHeaders(convertHeaders(headers));
    return httpRequest;
}

From source file:org.metaeffekt.dcc.commons.ant.HttpRequestTask.java

/**
 * Executes the task.//from   www  .jav a  2 s  .c o  m
 * 
 * @see org.apache.tools.ant.Task#execute()
 */
@Override
public void execute() {

    StringBuilder sb = new StringBuilder();
    sb.append(serverScheme).append("://").append(serverHostName).append(':').append(serverPort);
    sb.append("/").append(uri);
    String url = sb.toString();

    BasicCredentialsProvider credentialsProvider = null;
    if (username != null) {
        log("User: " + username, Project.MSG_DEBUG);
        credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(new AuthScope(serverHostName, serverPort),
                new UsernamePasswordCredentials(username, password));
    }

    HttpClient httpClient = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider)
            .build();

    try {
        switch (httpMethod) {
        case GET:
            HttpGet get = new HttpGet(url);
            doRequest(httpClient, get);
            break;
        case PUT:
            HttpPut put = new HttpPut(url);
            if (body == null) {
                body = "";
            }
            log("Setting body: " + body, Project.MSG_DEBUG);
            put.setEntity(new StringEntity(body, ContentType.create(contentType)));
            doRequest(httpClient, put);
            break;
        case POST:
            HttpPost post = new HttpPost(url);
            if (body == null) {
                body = "";
            }
            log("Setting body: " + body, Project.MSG_DEBUG);
            post.setEntity(new StringEntity(body, ContentType.create(contentType)));
            doRequest(httpClient, post);
            break;
        case DELETE:
            HttpDelete delete = new HttpDelete(url);
            doRequest(httpClient, delete);
            break;
        default:
            throw new IllegalArgumentException("HttpMethod " + httpMethod + " not supported!");
        }
    } catch (IOException e) {
        throw new BuildException(e);
    }
}

From source file:com.hoccer.api.FileCache.java

public String store(StreamableContent data, int secondsUntilExipred)
        throws ClientProtocolException, IOException, Exception {

    String url = ClientConfig.getFileCacheBaseUri() + "/" + UUID.randomUUID() + "/?expires_in="
            + secondsUntilExipred;//  www.  j  a v a 2  s  . c  o m
    LOG.finest("put uri = " + url);
    HttpPut request = new HttpPut(sign(url));

    InputStreamEntity entity = new InputStreamEntity(data.openNewInputStream(), data.getNewStreamLength());
    request.addHeader("Content-Disposition", " attachment; filename=\"" + data.getFilename() + "\"");
    entity.setContentType(data.getContentType());
    request.setEntity(entity);
    request.addHeader("Content-Type", data.getContentType());

    HttpResponse response = getHttpClient().execute(request);

    String responseString = convertResponseToString(response, false);
    LOG.finest("response = " + responseString);

    return responseString;
}

From source file:sabina.integration.TestScenario.java

private HttpUriRequest getHttpRequest(String method, String path, String body, boolean secure,
        String acceptType) {/* www .  j  a  v  a  2 s  .  c o  m*/

    if (body == null)
        body = "";

    try {
        String protocol = secure ? "https" : "http";
        String uri = protocol + "://localhost:" + port + path;

        if (method.equals("GET")) {
            HttpGet httpGet = new HttpGet(uri);
            httpGet.setHeader("Accept", acceptType);
            return httpGet;
        }

        if (method.equals("POST")) {
            HttpPost httpPost = new HttpPost(uri);
            httpPost.setHeader("Accept", acceptType);
            httpPost.setEntity(new StringEntity(body));
            return httpPost;
        }

        if (method.equals("PATCH")) {
            HttpPatch httpPatch = new HttpPatch(uri);
            httpPatch.setHeader("Accept", acceptType);
            httpPatch.setEntity(new StringEntity(body));
            return httpPatch;
        }

        if (method.equals("DELETE")) {
            HttpDelete httpDelete = new HttpDelete(uri);
            httpDelete.setHeader("Accept", acceptType);
            return httpDelete;
        }

        if (method.equals("PUT")) {
            HttpPut httpPut = new HttpPut(uri);
            httpPut.setHeader("Accept", acceptType);
            httpPut.setEntity(new StringEntity(body));
            return httpPut;
        }

        if (method.equals("HEAD"))
            return new HttpHead(uri);

        if (method.equals("TRACE"))
            return new HttpTrace(uri);

        if (method.equals("OPTIONS"))
            return new HttpOptions(uri);

        throw new IllegalArgumentException("Unknown method " + method);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.apache.olingo.server.core.ServiceDispatcherTest.java

private void helpTest(ServiceHandler handler, String path, String method, String payload, TestResult validator)
        throws Exception {
    beforeTest(handler);/*from ww  w. j  ava 2 s .  c o m*/

    DefaultHttpClient http = new DefaultHttpClient();

    String editUrl = "http://localhost:" + TOMCAT_PORT + "/" + path;
    HttpRequest request = new HttpGet(editUrl);
    if (method.equals("POST")) {
        HttpPost post = new HttpPost(editUrl);
        post.setEntity(new StringEntity(payload));
        request = post;
    } else if (method.equals("PUT")) {
        HttpPut put = new HttpPut(editUrl);
        put.setEntity(new StringEntity(payload));
        request = put;
    } else if (method.equals("DELETE")) {
        HttpDelete delete = new HttpDelete(editUrl);
        request = delete;
    }
    request.setHeader("Content-Type", "application/json;odata.metadata=minimal");
    http.execute(getLocalhost(), request);

    validator.validate();
    afterTest();
}

From source file:de.codecentric.boot.admin.zuul.filters.route.SimpleHostRoutingFilter.java

private CloseableHttpResponse forward(CloseableHttpClient httpclient, String verb, String uri,
        HttpServletRequest request, MultiValueMap<String, String> headers, MultiValueMap<String, String> params,
        InputStream requestEntity) throws Exception {
    Map<String, Object> info = this.helper.debug(verb, uri, headers, params, requestEntity);
    URL host = RequestContext.getCurrentContext().getRouteHost();
    HttpHost httpHost = getHttpHost(host);
    uri = StringUtils.cleanPath((host.getPath() + uri).replaceAll("/{2,}", "/"));
    HttpRequest httpRequest;/* www.  j  a va 2  s . c om*/
    int contentLength = request.getContentLength();
    InputStreamEntity entity = new InputStreamEntity(requestEntity, contentLength,
            request.getContentType() != null ? ContentType.create(request.getContentType()) : null);
    switch (verb.toUpperCase()) {
    case "POST":
        HttpPost httpPost = new HttpPost(uri + this.helper.getQueryString(params));
        httpRequest = httpPost;
        httpPost.setEntity(entity);
        break;
    case "PUT":
        HttpPut httpPut = new HttpPut(uri + this.helper.getQueryString(params));
        httpRequest = httpPut;
        httpPut.setEntity(entity);
        break;
    case "PATCH":
        HttpPatch httpPatch = new HttpPatch(uri + this.helper.getQueryString(params));
        httpRequest = httpPatch;
        httpPatch.setEntity(entity);
        break;
    default:
        httpRequest = new BasicHttpRequest(verb, uri + this.helper.getQueryString(params));
        log.debug(uri + this.helper.getQueryString(params));
    }
    try {
        httpRequest.setHeaders(convertHeaders(headers));
        log.debug(httpHost.getHostName() + " " + httpHost.getPort() + " " + httpHost.getSchemeName());
        CloseableHttpResponse zuulResponse = forwardRequest(httpclient, httpHost, httpRequest);
        RequestContext.getCurrentContext().set("zuulResponse", zuulResponse);
        this.helper.appendDebug(info, zuulResponse.getStatusLine().getStatusCode(),
                revertHeaders(zuulResponse.getAllHeaders()));
        return zuulResponse;
    } finally {
        // When HttpClient instance is no longer needed,
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        // httpclient.getConnectionManager().shutdown();
    }
}

From source file:org.deviceconnect.android.profile.restful.test.NormalCommonTestCase.java

/**
 * PUT?????.//  w ww  .j  av a 2 s .  c  o m
 * <pre>
 * ?HTTP
 * Method: PUT
 * Path: /battery?deviceId&accessToken=xxxx
 * </pre>
 * <pre>
 * ??
 * result?0???????
 * ???????????????
 * </pre>
 * 
 * @throws UnsupportedEncodingException ?Body?????
 */
public void testPutRequestParametersBothBodyAndParameterPart() throws UnsupportedEncodingException {
    StringBuilder builder = new StringBuilder();
    builder.append(DCONNECT_MANAGER_URI);
    builder.append("/unique/test/ping");
    builder.append("?");
    builder.append(DConnectProfileConstants.PARAM_DEVICE_ID + "=unknown");
    builder.append("&");
    builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN + "=" + getAccessToken());
    try {
        HttpPut request = new HttpPut(builder.toString());
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair(DConnectProfileConstants.PARAM_DEVICE_ID, getDeviceId()));
        params.add(new BasicNameValuePair(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN, getAccessToken()));
        request.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
        JSONObject root = sendRequest(request);
        assertResultOK(root);
    } catch (JSONException e) {
        fail("Exception in JSONObject." + e.getMessage());
    }
}