Example usage for org.apache.http.client.methods HttpPut HttpPut

List of usage examples for org.apache.http.client.methods HttpPut HttpPut

Introduction

In this page you can find the example usage for org.apache.http.client.methods HttpPut HttpPut.

Prototype

public HttpPut(final String uri) 

Source Link

Usage

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  w ww .  j  av a  2s  . c o 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.hoccer.api.Linccer.java

public void submitEnvironment() throws UpdateException, ClientProtocolException, IOException {
    HttpResponse response;//  w ww.jav  a 2  s  . c  om
    long startTime = 0;
    String uri = mConfig.getClientUri() + "/environment";
    try {
        HttpPut request = new HttpPut(sign(uri));
        request.setEntity(new StringEntity(mEnvironment.toJson().toString(), HTTP.UTF_8));
        startTime = System.currentTimeMillis();
        LOG.finest("submit environment uri = " + uri);
        LOG.finest("submit environment = " + mEnvironment.toJson().toString());
        response = getHttpClient().execute(request);
    } catch (JSONException e) {
        mEnvironmentStatus = null;
        throw new UpdateException(
                "could not update gps measurement for " + mConfig.getClientUri() + " because of " + e);
    } catch (UnsupportedEncodingException e) {
        mEnvironmentStatus = null;
        throw new UpdateException(
                "could not update gps measurement for " + mConfig.getClientUri() + " because of " + e);
    }

    if (response.getStatusLine().getStatusCode() != 201) {
        try {
            mEnvironmentStatus = null;
            throw new UpdateException("could not update environment because server " + uri + " responded with "
                    + response.getStatusLine().getStatusCode() + ": "
                    + convertResponseToString(response, true));
        } catch (ParseException e) {
        } catch (IOException e) {
        }
        throw new UpdateException("could not update environment because server " + uri + " responded with "
                + response.getStatusLine().getStatusCode() + " and an unparsable body");
    }

    try {
        mEnvironmentStatus = new EnvironmentStatus(convertResponseToJsonObject(response));
    } catch (Exception e) {
        mEnvironmentStatus = null;
        throw new UpdateException("could not update environment because server responded with "
                + response.getStatusLine().getStatusCode() + " and an ill formed body: " + e.getMessage());
    }
    int latency = (int) (System.currentTimeMillis() - startTime);

    mEnvironment.setNetworkLatency(latency);
}

From source file:uk.co.visalia.brightpearl.apiclient.http.httpclient4.HttpClient4Client.java

private HttpRequestBase createBaseRequest(Method method, String url, String body) {
    if (method == Method.GET) {
        return new HttpGet(url);
    } else if (method == Method.POST) {
        HttpPost post = new HttpPost(url);
        addBody(post, body);/*from   w w  w  .  j a v a2s.  com*/
        return post;
    } else if (method == Method.PUT) {
        HttpPut put = new HttpPut(url);
        addBody(put, body);
        return put;
    } else if (method == Method.DELETE) {
        return new HttpDelete(url);
    } else if (method == Method.OPTIONS) {
        return new HttpOptions(url);
    }
    throw new IllegalArgumentException("HTTP method " + method + " is not supported by this client");
}

From source file:at.ac.tuwien.dsg.mlr.util.RestfulWSClient.java

public int callPutMethodRC(String xmlString) {
    int statusCode = 0;

    try {//from  w w w .  j  ava 2 s . com

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

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

        Logger.getLogger(RestfulWSClient.class.getName()).log(Level.INFO, "Status Code: " + statusCode);

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

    }
    return statusCode;
}

From source file:com.esri.geoportal.commons.gpt.client.Client.java

/**
 * Publishes a document./*from w w w .  ja  va 2s .  c om*/
 *
 * @param data data to publish
 * @param forceAdd <code>true</code> to force add.
 * @return response information
 * @throws IOException if reading response fails
 * @throws URISyntaxException if URL has invalid syntax
 */
public PublishResponse publish(PublishRequest data, boolean forceAdd) throws IOException, URISyntaxException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    String json = mapper.writeValueAsString(data);
    StringEntity entity = new StringEntity(json);

    List<String> ids = !forceAdd ? queryIds(data.src_uri_s) : Collections.emptyList();
    HttpRequestBase request;
    switch (ids.size()) {
    case 0: {
        HttpPut put = new HttpPut(url.toURI().resolve(REST_ITEM_URL));
        put.setConfig(DEFAULT_REQUEST_CONFIG);
        put.setEntity(entity);
        put.setHeader("Content-Type", "application/json");
        request = put;
    }
        break;
    case 1: {
        HttpPut put = new HttpPut(url.toURI().resolve(REST_ITEM_URL + "/" + ids.get(0)));
        put.setConfig(DEFAULT_REQUEST_CONFIG);
        put.setEntity(entity);
        put.setHeader("Content-Type", "application/json");
        request = put;
    }
        break;
    default:
        throw new IOException(String.format("Error updating item: %s", data.src_uri_s));
    }

    try (CloseableHttpResponse httpResponse = execute(request);
            InputStream contentStream = httpResponse.getEntity().getContent();) {
        if (httpResponse.getStatusLine().getStatusCode() >= 400) {
            throw new HttpResponseException(httpResponse.getStatusLine().getStatusCode(),
                    httpResponse.getStatusLine().getReasonPhrase());
        }
        String reasonMessage = httpResponse.getStatusLine().getReasonPhrase();
        String responseContent = IOUtils.toString(contentStream, "UTF-8");
        LOG.trace(String.format("RESPONSE: %s, %s", responseContent, reasonMessage));
        return mapper.readValue(responseContent, PublishResponse.class);
    }
}

From source file:xyz.cloudbans.client.DefaultClient.java

@Override
public Future<BanResponse> updateBan(BanRequest request) {
    HttpPut httpRequest = new HttpPut(buildSafe(createUri("/ban/" + request.getId())));
    initHeaders(httpRequest);/* ww w  .ja va2  s .  c o  m*/
    httpRequest.setEntity(createEntity(request));

    return client.execute(new BasicAsyncRequestProducer(URIUtils.extractHost(config.getBaseUri()), httpRequest),
            SerializerConsumer.create(config.getSerializer(), BanResponse.class),
            DeafFutureCallback.<BanResponse>instance());
}

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

public JSONObject put(URI path, Collection<Header> headers, JSONObject json)
        throws ProtocolException, RESTException {
    // create request + entity
    HttpPut put = new HttpPut(uri.resolve(path));
    put.addHeader("Content-Type", "application/json");
    try {// ww  w . j  av  a 2  s. c  o  m
        put.setEntity(new StringEntity(json.toString()));
    } catch (UnsupportedEncodingException uex) {
        throw new RuntimeException(uex);
    }

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

From source file:com.arrow.acn.client.api.DeviceStateApi.java

public StatusModel transSucceeded(String deviceHid, String transHid) {
    String method = "transSucceeded";
    try {/*w ww  .ja  va 2  s  .  com*/
        URI uri = buildUri(String.format(TRANS_SUCCEEDED_URL, deviceHid, transHid));
        StatusModel result = execute(new HttpPut(uri), StatusModel.class);
        log(method, result);
        return result;
    } catch (Throwable e) {
        logError(method, e);
        throw new AcnClientException(method, e);
    }
}

From source file:com.linkedin.multitenant.db.RocksdbDatabase.java

@Override
public DatabaseResult doInsert(Query q) {
    HttpPut put = new HttpPut(m_connStr + q.getKey());

    ByteArrayEntity bae = new ByteArrayEntity(q.getValue());
    bae.setContentType("octet-stream");
    put.setEntity(bae);/*w w w. java 2s  .co m*/

    try {
        String responseBody = m_client.execute(put, m_handler);
        m_log.debug("Write response: " + responseBody);
        return DatabaseResult.OK;
    } catch (Exception e) {
        m_log.error("Error in executing doInsert", e);
        return DatabaseResult.FAIL;
    }
}

From source file:neal.http.impl.httpstack.HttpClientStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *///from  w ww . ja v a2  s.c o m
@SuppressWarnings("deprecation")
/* protected */ static HttpUriRequest createHttpRequest(Request<?> request,
        Map<String, String> additionalHeaders) throws HttpErrorCollection.AuthFailureError {
    switch (request.getMethod()) {
    case Method.DEPRECATED_GET_OR_POST: {
        // This is the deprecated way that needs to be handled for backwards compatibility.
        // If the request's post body is null, then the assumption is that the request is
        // GET.  Otherwise, it is assumed that the request is a POST.
        byte[] postBody = request.getPostBody();
        if (postBody != null) {
            HttpPost postRequest = new HttpPost(request.getUrl());
            postRequest.addHeader(HEADER_CONTENT_TYPE, request.getPostBodyContentType());
            HttpEntity entity;
            entity = new ByteArrayEntity(postBody);
            postRequest.setEntity(entity);
            return postRequest;
        } else {
            return new HttpGet(request.getUrl());
        }
    }
    case Method.GET:
        return new HttpGet(request.getUrl());
    case Method.DELETE:
        return new HttpDelete(request.getUrl());
    case Method.POST: {
        HttpPost postRequest = new HttpPost(request.getUrl());
        postRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(postRequest, request);
        return postRequest;
    }
    case Method.PUT: {
        HttpPut putRequest = new HttpPut(request.getUrl());
        putRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(putRequest, request);
        return putRequest;
    }
    case Method.HEAD:
        return new HttpHead(request.getUrl());
    case Method.OPTIONS:
        return new HttpOptions(request.getUrl());
    case Method.TRACE:
        return new HttpTrace(request.getUrl());
    case Method.PATCH: {
        HttpPatch patchRequest = new HttpPatch(request.getUrl());
        patchRequest.addHeader(HEADER_CONTENT_TYPE, request.getBodyContentType());
        setEntityIfNonEmptyBody(patchRequest, request);
        return patchRequest;
    }
    default:
        throw new IllegalStateException("Unknown request method.");
    }
}