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.activiti.service.activiti.ProcessInstanceService.java

public void updateVariable(ServerConfig serverConfig, String processInstanceId, String variableName,
        ObjectNode objectNode) {/* www  .jav a2s.  c  o  m*/
    URIBuilder builder = clientUtil.createUriBuilder(
            MessageFormat.format(RUNTIME_PROCESS_INSTANCE_VARIABLE_URL, processInstanceId, variableName));
    HttpPut put = clientUtil.createPut(builder, serverConfig);
    put.setEntity(clientUtil.createStringEntity(objectNode.toString()));
    clientUtil.executeRequest(put, serverConfig);
}

From source file:com.citruspay.mobile.payment.client.rest.RESTClient.java

public JSONObject put(URI path, Collection<Header> headers, Map<String, String> params)
        throws ProtocolException, RESTException {

    List<NameValuePair> pairs = new ArrayList<NameValuePair>();
    for (Map.Entry<String, String> param : params.entrySet()) {
        pairs.add(new BasicNameValuePair(param.getKey(), param.getValue()));
    }/*from w  ww  .j av  a 2  s  . c  om*/
    // create request + entity
    HttpPut put = new HttpPut(uri.resolve(path));

    try {
        put.setEntity(new UrlEncodedFormEntity(pairs));
    } catch (UnsupportedEncodingException uex) {
        throw new RuntimeException(uex);
    }

    // execute request
    return execute(put, headers);
}

From source file:v7cr.V7CR.java

BSONBackedObject storeFile(File file, String fileName, String mimeType) throws IOException {
    HttpClient http = new DefaultHttpClient();
    HttpPut put = new HttpPut("http://0.0.0.0:8088/upload/v7cr");
    put.setEntity(new FileEntity(file, mimeType));
    HttpResponse response = http.execute(put);
    if (response.getStatusLine().getStatusCode() != 200) {
        throw new IOException("failed to save " + fileName + ": " + response.getStatusLine());
    }//from  w  ww .j  a va 2 s  .c  om

    String sha = IOUtils.toString(response.getEntity().getContent());
    BSONObject r = new BasicBSONObject("sha", sha);
    r.put("filename", fileName);
    r.put("contentType", mimeType);
    r.put("length", file.length());
    return BSONBackedObjectLoader.wrap(r, null);
}

From source file:com.twotoasters.android.hoot.HootTransportHttpClient.java

@Override
public HootResult synchronousExecute(HootRequest request) {

    HttpRequestBase requestBase = null;/*from w  w  w  .  j  a  v a 2s.c  o m*/
    HootResult result = request.getResult();
    try {
        String uri = request.buildUri().toString();
        switch (request.getOperation()) {
        case DELETE:
            requestBase = new HttpDelete(uri);
            break;
        case GET:
            requestBase = new HttpGet(uri);
            break;
        case PUT:
            HttpPut put = new HttpPut(uri);
            put.setEntity(getEntity(request));
            requestBase = put;
            break;
        case POST:
            HttpPost post = new HttpPost(uri);
            post.setEntity(getEntity(request));
            requestBase = post;
            break;
        case HEAD:
            requestBase = new HttpHead(uri);
            break;
        }
    } catch (UnsupportedEncodingException e1) {
        result.setException(e1);
        e1.printStackTrace();
        return result;
    } catch (IOException e) {
        result.setException(e);
        e.printStackTrace();
        return result;
    }

    synchronized (mRequestBaseMap) {
        mRequestBaseMap.put(request, requestBase);
    }
    if (request.getHeaders() != null && request.getHeaders().size() > 0) {
        for (Object propertyKey : request.getHeaders().keySet()) {
            requestBase.addHeader((String) propertyKey, (String) request.getHeaders().get(propertyKey));
        }
    }

    InputStream is = null;
    try {
        Log.v(TAG, "URI: [" + requestBase.getURI().toString() + "]");
        HttpResponse response = mClient.execute(requestBase);

        if (response != null) {
            result.setResponseCode(response.getStatusLine().getStatusCode());
            Map<String, List<String>> headers = new HashMap<String, List<String>>();
            for (Header header : response.getAllHeaders()) {
                List<String> values = new ArrayList<String>();
                values.add(header.getValue());
                headers.put(header.getName(), values);
            }
            result.setHeaders(headers);
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                is = entity.getContent();
                result.setResponseStream(new BufferedInputStream(is));
                request.deserializeResult();
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
        result.setException(e);
    } finally {
        requestBase = null;
        synchronized (mRequestBaseMap) {
            mRequestBaseMap.remove(request);
        }
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return result;
}

From source file:org.b3log.latke.urlfetch.bae.BAEURLFetchService.java

@Override
public HTTPResponse fetch(final HTTPRequest request) throws IOException {
    final HttpClient httpClient = new DefaultHttpClient();

    final URL url = request.getURL();
    final HTTPRequestMethod requestMethod = request.getRequestMethod();

    HttpUriRequest httpUriRequest = null;

    try {//from w w w . j  a v a 2 s  . c  o m
        final byte[] payload = request.getPayload();

        switch (requestMethod) {

        case GET:
            final HttpGet httpGet = new HttpGet(url.toURI());

            // FIXME: GET with payload
            httpUriRequest = httpGet;
            break;

        case DELETE:
            httpUriRequest = new HttpDelete(url.toURI());
            break;

        case HEAD:
            httpUriRequest = new HttpHead(url.toURI());
            break;

        case POST:
            final HttpPost httpPost = new HttpPost(url.toURI());

            if (null != payload) {
                httpPost.setEntity(new ByteArrayEntity(payload));
            }
            httpUriRequest = httpPost;
            break;

        case PUT:
            final HttpPut httpPut = new HttpPut(url.toURI());

            if (null != payload) {
                httpPut.setEntity(new ByteArrayEntity(payload));
            }
            httpUriRequest = httpPut;
            break;

        default:
            throw new RuntimeException("Unsupported HTTP request method[" + requestMethod.name() + "]");
        }
    } catch (final Exception e) {
        LOGGER.log(Level.SEVERE, "URL fetch failed", e);

        throw new IOException("URL fetch failed [msg=" + e.getMessage() + ']');
    }

    final List<HTTPHeader> headers = request.getHeaders();

    for (final HTTPHeader header : headers) {
        httpUriRequest.addHeader(header.getName(), header.getValue());
    }

    final HttpResponse res = httpClient.execute(httpUriRequest);

    final HTTPResponse ret = new HTTPResponse();

    ret.setContent(EntityUtils.toByteArray(res.getEntity()));
    ret.setResponseCode(res.getStatusLine().getStatusCode());

    return ret;
}

From source file:at.ac.tuwien.dsg.cloudlyra.utils.QualityEvaluatorREST.java

public void callQualityEvaluator(String xmlString) {

    try {/*  w ww.  j av a2  s.c o m*/
        String url = "http://" + ip + ":" + port + "/RESTWSTEST/webresources/daf";

        //  String url = "http://" + ip + ":" + port + "/QualityEvaluator/webresources/QualityEvaluator";
        //HttpGet method = new HttpGet(url);
        StringEntity inputKeyspace = new StringEntity(xmlString);

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

        System.out.println("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);
        }

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

    }

}

From source file:mx.ipn.escom.supernaut.nile.logic.CommonBean.java

@Override
@PrePassivate/* w w  w . j  a  v  a  2s  . c  o m*/
public void commitModel() {
    HttpPut request = new HttpPut(baseUri + getPkAsParams());
    request.addHeader(JSON_OUT_HEAD);
    HttpResponse response;
    try {
        request.setEntity(new InputStreamEntity(streamedMarshall()));
        response = client.execute(HOST, request);
    } catch (IOException ex) {
        throw new RuntimeException(ex);
    }
    StatusLine statusLine = response.getStatusLine();
    if (statusLine.getStatusCode() < 200 || statusLine.getStatusCode() > 299)
        throw new RuntimeException(statusLine.getReasonPhrase());
}

From source file:nl.esciencecenter.octopus.webservice.api.SandboxedJob.java

private void putState2Callback() throws IOException {
    if (request != null && request.status_callback_url != null) {
        String body = getStatusResponse().toJson();
        HttpPut put = new HttpPut(request.status_callback_url);
        HttpEntity entity = new StringEntity(body, ContentType.APPLICATION_JSON);
        put.setEntity(entity);
        httpClient.execute(put);/*from   w w  w  .  j av  a2s .  c  o  m*/
    }
}

From source file:com.github.seratch.signedrequest4j.SignedRequestApacheHCImpl.java

/**
 * {@inheritDoc}// w  w  w  .jav a  2s.  co  m
 */
@Override
public HttpResponse doRequest(String url, HttpMethod method, Map<String, Object> requestParameters,
        String charset) throws IOException {

    HttpEntity entity = null;
    if (method == HttpMethod.GET) {
        List<NameValuePair> params = toNameValuePairList(requestParameters);
        String queryString = URLEncodedUtils.format(params, "UTF-8");
        if (queryString != null && !queryString.isEmpty()) {
            url = url.contains("?") ? url + "&" + queryString : url + "?" + queryString;
        }
    } else {
        List<NameValuePair> params = toNameValuePairList(requestParameters);
        entity = new UrlEncodedFormEntity(params, "UTF-8");
    }

    // read get parameters for signature base string
    readQueryStringAndAddToSignatureBaseString(url);

    HttpClient httpClient = new DefaultHttpClient();
    HttpUriRequest request = getRequest(method, url);
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, connectTimeoutMillis);
    httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, readTimeoutMillis);
    httpClient.getParams().setParameter(CoreProtocolPNames.USER_AGENT, USER_AGENT);
    httpClient.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, charset);

    for (String name : headersToOverwrite.keySet()) {
        request.setHeader(name, headersToOverwrite.get(name));
    }

    String oAuthNonce = String.valueOf(new SecureRandom().nextLong());
    Long oAuthTimestamp = System.currentTimeMillis() / 1000;
    String signature = getSignature(url, method, oAuthNonce, oAuthTimestamp);
    String authorizationHeader = getAuthorizationHeader(signature, oAuthNonce, oAuthTimestamp);
    request.setHeader("Authorization", authorizationHeader);

    if (entity != null) {
        if (method == HttpMethod.POST) {
            HttpPost postRequest = (HttpPost) request;
            postRequest.setEntity(entity);
        } else if (method == HttpMethod.PUT) {
            HttpPut putRequest = (HttpPut) request;
            putRequest.setEntity(entity);
        }
    }

    org.apache.http.HttpResponse apacheHCResponse = httpClient.execute(request);
    if (apacheHCResponse.getStatusLine().getStatusCode() >= 400) {
        HttpResponse httpResponse = toReturnValue(apacheHCResponse, charset);
        throw new HttpException(apacheHCResponse.getStatusLine().getReasonPhrase(), httpResponse);
    }
    return toReturnValue(apacheHCResponse, charset);

}