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.hoccer.tools.HttpHelper.java

public static String putText(String pUri, String pData)
        throws IOException, HttpClientException, HttpServerException {
    HttpPut put = new HttpPut(pUri);
    insert(pData, "text/xml", "text/xml", put);
    StatusLine statusLine = executeHTTPMethod(put, PUT_TIMEOUT).getStatusLine();
    return statusLine.getStatusCode() + " " + statusLine.getReasonPhrase();
}

From source file:com.okta.sdk.impl.http.httpclient.HttpClientRequestFactory.java

/**
 * Creates an HttpClient method object based on the specified request and
 * populates any parameters, headers, etc. from the original request.
 *
 * @param request        The request to convert to an HttpClient method object.
 * @param previousEntity The optional, previous HTTP entity to reuse in the new request.
 * @return The converted HttpClient method object with any parameters,
 *         headers, etc. from the original request set.
 *///w  w w.  j  a va 2 s  .c  om
HttpRequestBase createHttpClientRequest(Request request, HttpEntity previousEntity) {

    HttpMethod method = request.getMethod();
    URI uri = getFullyQualifiedUri(request);
    InputStream body = request.getBody();
    long contentLength = request.getHeaders().getContentLength();

    HttpRequestBase base;

    switch (method) {
    case DELETE:
        base = new HttpDelete(uri);
        break;
    case GET:
        base = new HttpGet(uri);
        break;
    case HEAD:
        base = new HttpHead(uri);
        break;
    case POST:
        base = new HttpPost(uri);
        ((HttpEntityEnclosingRequestBase) base).setEntity(new RepeatableInputStreamEntity(request));
        break;
    case PUT:
        base = new HttpPut(uri);

        // Enable 100-continue support for PUT operations, since this is  where we're potentially uploading
        // large amounts of data and want to find out as early as possible if an operation will fail. We
        // don't want to do this for all operations since it will cause extra latency in the network
        // interaction.
        base.setConfig(RequestConfig.copy(defaultRequestConfig).setExpectContinueEnabled(true).build());

        if (previousEntity != null) {
            ((HttpEntityEnclosingRequestBase) base).setEntity(previousEntity);
        } else if (body != null) {
            HttpEntity entity = new RepeatableInputStreamEntity(request);
            if (contentLength < 0) {
                entity = newBufferedHttpEntity(entity);
            }
            ((HttpEntityEnclosingRequestBase) base).setEntity(entity);
        }
        break;
    default:
        throw new IllegalArgumentException("Unrecognized HttpMethod: " + method);
    }

    base.setProtocolVersion(HttpVersion.HTTP_1_1);

    applyHeaders(base, request);

    return base;
}

From source file:org.xmlsh.internal.commands.http.java

@Override
public int run(List<XValue> args) throws Exception {

    Options opts = new Options(
            "retry:,get:,put:,post:,head:,options:,delete:,connectTimeout:,contentType:,readTimeout:,+useCaches,+followRedirects,user:,password:,H=add-header:+,disableTrust:,keystore:,keypass:,sslproto:,output-headers=ohead:");
    opts.parse(args);//from ww w . j  a v  a2  s.  c  om

    setSerializeOpts(getSerializeOpts(opts));

    HttpRequestBase method;

    String surl = null;

    if (opts.hasOpt("get")) {
        surl = opts.getOptString("get", null);
        method = new HttpGet(surl);
    } else if (opts.hasOpt("put")) {
        surl = opts.getOptString("put", null);
        method = new HttpPut(surl);
        ((HttpPut) method).setEntity(getInputEntity(opts));
    } else if (opts.hasOpt("post")) {
        surl = opts.getOptString("post", null);
        method = new HttpPost(surl);
        ((HttpPost) method).setEntity(getInputEntity(opts));

    } else if (opts.hasOpt("head")) {
        surl = opts.getOptString("head", null);
        method = new HttpHead(surl);
    } else if (opts.hasOpt("options")) {
        surl = opts.getOptString("options", null);
        method = new HttpOptions(surl);
    } else if (opts.hasOpt("delete")) {
        surl = opts.getOptString("delete", null);
        method = new HttpDelete(surl);
    } else if (opts.hasOpt("trace")) {
        surl = opts.getOptString("trace", null);
        method = new HttpTrace(surl);
    } else {
        surl = opts.getRemainingArgs().get(0).toString();
        method = new HttpGet(surl);
    }

    if (surl == null) {
        usage();
        return 1;
    }

    int ret = 0;

    HttpHost host = new HttpHost(surl);

    DefaultHttpClient client = new DefaultHttpClient();

    setOptions(client, host, opts);

    List<XValue> headers = opts.getOptValues("H");
    if (headers != null) {
        for (XValue v : headers) {
            StringPair pair = new StringPair(v.toString(), '=');
            method.addHeader(pair.getLeft(), pair.getRight());
        }

    }

    int retry = opts.getOptInt("retry", 0);
    long delay = 1000;

    HttpResponse resp = null;

    do {
        try {
            resp = client.execute(method);
            break;
        } catch (IOException e) {
            mShell.printErr("Exception running http" + ((retry > 0) ? " retrying ... " : ""), e);
            if (retry > 0) {
                Thread.sleep(delay);
                delay *= 2;
            } else
                throw e;
        }
    } while (retry-- > 0);

    HttpEntity respEntity = resp.getEntity();
    if (respEntity != null) {
        InputStream ins = respEntity.getContent();
        if (ins != null) {
            try {
                Util.copyStream(ins, getStdout().asOutputStream(getSerializeOpts()));
            } finally {
                ins.close();
            }
        }
    }

    ret = resp.getStatusLine().getStatusCode();
    if (opts.hasOpt("output-headers"))
        writeHeaders(opts.getOptStringRequired("output-headers"), resp.getStatusLine(), resp.getAllHeaders());

    return ret;
}

From source file:io.crate.integrationtests.SQLHttpIntegrationTest.java

protected String upload(String table, String content) throws IOException {
    String digest = blobDigest(content);
    String url = Blobs.url(address, table, digest);
    HttpPut httpPut = new HttpPut(url);
    httpPut.setEntity(new StringEntity(content));

    CloseableHttpResponse response = httpClient.execute(httpPut);
    assertThat(response.getStatusLine().getStatusCode(), is(201));
    response.close();//from  w  w  w.  j a va  2 s. c om

    return url;
}

From source file:com.demo.wtm.service.RestService.java

public void execute(String url, RequestMethod method, boolean authentication) throws Exception {

    this.authentication = authentication;

    switch (method) {
    case GET: {//from w w  w  .j  ava2s. c  o  m
        HttpGet request = new HttpGet(url + addGetParams());
        request = (HttpGet) addHeaderParams(request);
        request = (HttpGet) addBodyParams(request);
        executeRequest(request, url);
        break;
    }
    case POST: {
        HttpPost request = new HttpPost(url + addGetParams());
        request = (HttpPost) addHeaderParams(request);
        request = (HttpPost) addBodyParams(request);
        executeRequest(request, url);
        break;
    }
    case PUT: {
        HttpPut request = new HttpPut(url + addGetParams());
        request = (HttpPut) addHeaderParams(request);
        request = (HttpPut) addBodyParams(request);
        executeRequest(request, url);
        break;
    }
    case DELETE: {
        HttpDelete request = new HttpDelete(url + addGetParams());
        request = (HttpDelete) addHeaderParams(request);
        request = (HttpDelete) addBodyParams(request);
        executeRequest(request, url);
    }
    }
}

From source file:com.srotya.tau.ui.rules.RulesManager.java

public short saveRule(UserBean ub, Tenant tenant, Rule currRule) throws Exception {
    if (currRule == null || tenant == null) {
        logger.info("Rule was null can't save");
        return -1;
    }/*from   w  w  w. ja  v a  2  s  .  co  m*/
    RuleValidator.getInstance().validate(currRule);
    logger.info("Rule is valid attempting to save");
    CloseableHttpClient client = Utils.buildClient(am.getBaseUrl(), am.getConnectTimeout(),
            am.getRequestTimeout());
    HttpPut put = new HttpPut(
            am.getBaseUrl() + RULES_URL + "/" + tenant.getTenantId() + "/" + currRule.getRuleId());
    if (am.isEnableAuth()) {
        put.addHeader(BapiLoginDAO.X_SUBJECT_TOKEN, ub.getToken());
        put.addHeader(BapiLoginDAO.HMAC, ub.getHmac());
    }
    StringEntity entity = new StringEntity(RuleSerializer.serializeRuleToJSONString(currRule, false),
            ContentType.APPLICATION_JSON);
    put.setEntity(entity);
    CloseableHttpResponse resp = client.execute(put);
    String result = EntityUtils.toString(resp.getEntity());
    return Short.parseShort(result);
}

From source file:org.dthume.spring.http.client.httpcomponents.HttpComponentsClientHttpRequest.java

private HttpUriRequest createRequest() {
    final URI requestUri = getURI();
    final HttpMethod requestMethod = getMethod();

    switch (requestMethod) {
    case DELETE://from   w  w w  .  ja  va2s  . c om
        return new HttpDelete(requestUri);
    case GET:
        return new HttpGet(requestUri);
    case HEAD:
        return new HttpHead(requestUri);
    case PUT:
        return new HttpPut(requestUri);
    case POST:
        return new HttpPost(requestUri);
    case OPTIONS:
        return new HttpOptions(requestUri);
    default:
        final String msg = "Unknown Http Method: " + requestMethod;
        throw new IllegalArgumentException(msg);
    }
}

From source file:org.apache.edgent.connectors.http.runtime.HttpRequester.java

@Override
public R apply(T t) {

    if (client == null)
        client = clientCreator.get();//from  w  ww . jav a2s . com

    String m = method.apply(t);
    String uri = url.apply(t);
    HttpUriRequest request;

    switch (m) {

    case HttpGet.METHOD_NAME:
        request = new HttpGet(uri);
        break;
    case HttpDelete.METHOD_NAME:
        request = new HttpDelete(uri);
        break;
    case HttpPost.METHOD_NAME:
        request = new HttpPost(uri);
        break;
    case HttpPut.METHOD_NAME:
        request = new HttpPut(uri);
        break;

    default:
        throw new IllegalArgumentException();
    }

    // If entity is not null means http request should have a body
    if (entity != null) {

        HttpEntity body = entity.apply(t);

        if (request instanceof HttpEntityEnclosingRequest == false) {
            throw new IllegalArgumentException("Http request does not support body");
        }

        ((HttpEntityEnclosingRequest) request).setEntity(body);
    }

    try {
        try (CloseableHttpResponse response = client.execute(request)) {
            return responseProcessor.apply(t, response);
        }

    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.wso2.dss.integration.test.odata.ODataTestUtils.java

public static int sendPUT(String endpoint, String content, Map<String, String> headers) throws IOException {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPut httpPut = new HttpPut(endpoint);
    for (String headerType : headers.keySet()) {
        httpPut.setHeader(headerType, headers.get(headerType));
    }//from w w w.j a  v  a 2s. c  o  m
    if (null != content) {
        HttpEntity httpEntity = new ByteArrayEntity(content.getBytes("UTF-8"));
        if (headers.get("Content-Type") == null) {
            httpPut.setHeader("Content-Type", "application/json");
        }
        httpPut.setEntity(httpEntity);
    }
    HttpResponse httpResponse = httpClient.execute(httpPut);
    return httpResponse.getStatusLine().getStatusCode();
}

From source file:me.xiaopan.android.gohttp.HttpClientNetManager.java

private HttpUriRequest httpRequest2HttpUriRequest(HttpRequest httpRequest) {
    HttpUriRequest httpUriRequest = null;
    switch (httpRequest.getMethod()) {
    case GET://from   w w w  .  ja  v a 2  s  . c o  m
        String url = getUrlByParams(true, httpRequest.getUrl(), httpRequest.getParams());
        HttpGet httGet = new HttpGet(url);
        appendHeaders(httGet, httpRequest.getHeaders());
        httpUriRequest = httGet;
        break;
    case POST:
        HttpPost httPost = new HttpPost(httpRequest.getUrl());
        appendHeaders(httPost, httpRequest.getHeaders());

        HttpEntity httpPostEntity = httpRequest.getHttpEntity();
        if (httpPostEntity == null && httpRequest.getParams() != null) {
            httpPostEntity = httpRequest.getParams().getEntity();
        }
        if (httpPostEntity != null) {
            httPost.setEntity(httpPostEntity);
        }
        httpUriRequest = httPost;
        break;
    case DELETE:
        String deleteUrl = getUrlByParams(true, httpRequest.getUrl(), httpRequest.getParams());
        HttpDelete httDelete = new HttpDelete(deleteUrl);
        appendHeaders(httDelete, httpRequest.getHeaders());
        httpUriRequest = httDelete;
        break;
    case PUT:
        HttpPut httpPut = new HttpPut(httpRequest.getUrl());
        appendHeaders(httpPut, httpRequest.getHeaders());

        HttpEntity httpPutEntity = httpRequest.getHttpEntity();
        if (httpPutEntity == null && httpRequest.getParams() != null) {
            httpPutEntity = httpRequest.getParams().getEntity();
        }
        if (httpPutEntity != null) {
            httpPut.setEntity(httpPutEntity);
        }
        httpUriRequest = httpPut;
        break;
    }
    return httpUriRequest;
}