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:org.opendaylight.infrautils.diagstatus.shell.HttpClient.java

public HttpResponse sendRequest(HttpRequest request) throws Exception {
    CloseableHttpClient httpclient = HttpClients.createDefault();
    if (httpclient == null) {
        throw new ClientProtocolException("Couldn't create an HTTP client");
    }/* w ww .j  a va2 s  .c  o m*/
    RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(request.getTimeout())
            .setConnectTimeout(request.getTimeout()).build();
    HttpRequestBase httprequest;
    String method = request.getMethod();
    if (method.equalsIgnoreCase("GET")) {
        httprequest = new HttpGet(request.getUri());
    } else if (method.equalsIgnoreCase("POST")) {
        httprequest = new HttpPost(request.getUri());
        if (request.getEntity() != null) {
            StringEntity sentEntity = new StringEntity(request.getEntity());
            sentEntity.setContentType(request.getContentType());
            ((HttpEntityEnclosingRequestBase) httprequest).setEntity(sentEntity);
        }
    } else if (method.equalsIgnoreCase("PUT")) {
        httprequest = new HttpPut(request.getUri());
        if (request.getEntity() != null) {
            StringEntity sentEntity = new StringEntity(request.getEntity());
            sentEntity.setContentType(request.getContentType());
            ((HttpEntityEnclosingRequestBase) httprequest).setEntity(sentEntity);
        }
    } else if (method.equalsIgnoreCase("DELETE")) {
        httprequest = new HttpDelete(request.getUri());
    } else {
        httpclient.close();
        throw new IllegalArgumentException(
                "This profile class only supports GET, POST, PUT, and DELETE methods");
    }
    httprequest.setConfig(requestConfig);
    // add request headers
    Iterator<String> headerIterator = request.getHeaders().keySet().iterator();
    while (headerIterator.hasNext()) {
        String header = headerIterator.next();
        Iterator<String> valueIterator = request.getHeaders().get(header).iterator();
        while (valueIterator.hasNext()) {
            httprequest.addHeader(header, valueIterator.next());
        }
    }
    CloseableHttpResponse response = httpclient.execute(httprequest);
    try {
        int httpResponseCode = response.getStatusLine().getStatusCode();
        HashMap<String, List<String>> headerMap = new HashMap<>();
        // copy response headers
        HeaderIterator it = response.headerIterator();
        while (it.hasNext()) {
            Header nextHeader = it.nextHeader();
            String name = nextHeader.getName();
            String value = nextHeader.getValue();
            if (headerMap.containsKey(name)) {
                headerMap.get(name).add(value);
            } else {
                List<String> list = new ArrayList<>();
                list.add(value);
                headerMap.put(name, list);
            }
        }
        if (httpResponseCode > 299) {
            return new HttpResponse(httpResponseCode, response.getStatusLine().getReasonPhrase(), headerMap);
        }
        Optional<HttpEntity> receivedEntity = Optional.ofNullable(response.getEntity());
        String httpBody = receivedEntity.isPresent() ? EntityUtils.toString(receivedEntity.get()) : null;
        return new HttpResponse(response.getStatusLine().getStatusCode(), httpBody, headerMap);
    } finally {
        response.close();
    }
}

From source file:com.oplay.nohelper.volley.toolbox.HttpClientStack.java

/**
 * Creates the appropriate subclass of HttpUriRequest for passed in request.
 *///from   ww  w.  j a v a2  s .  c  o m
@SuppressWarnings("deprecation")
public static HttpUriRequest createHttpRequest(Request<?> request, Map<String, String> additionalHeaders)
        throws 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.");
    }
}

From source file:com.temenos.useragent.generic.http.DefaultHttpClient.java

@Override
public HttpResponse put(String url, HttpRequest request) {
    logHttpRequest(url, request);/*  w w  w.ja v a  2  s .  co m*/
    CloseableHttpClient client = HttpClientBuilder.create()
            .setDefaultCredentialsProvider(DefaultHttpClientHelper.getBasicCredentialProvider()).build();
    HttpPut putRequest = new HttpPut(url);
    DefaultHttpClientHelper.buildRequestHeaders(request, putRequest);
    putRequest.setEntity(new StringEntity(request.payload(), "UTF-8"));
    try {
        CloseableHttpResponse httpResponse = client.execute(putRequest);
        HttpEntity responseEntity = httpResponse.getEntity();
        return handleResponse(httpResponse, responseEntity);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

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

/**
 * deviceId??ondeviceorientation???.//from   w w w  .  ja  v a2s  .  c om
 * <pre>
 * ?HTTP
 * Method: PUT
 * Path: /deviceorientation/ondeviceorientation?deviceId=
 * </pre>
 * <pre>
 * ??
 * result?1???????
 * </pre>
 */
public void testPutOnDeviceOrientation002() {
    URIBuilder builder = TestURIBuilder.createURIBuilder();
    builder.setProfile(DeviceOrientationProfileConstants.PROFILE_NAME);
    builder.setAttribute(DeviceOrientationProfileConstants.ATTRIBUTE_ON_DEVICE_ORIENTATION);
    builder.addParameter(DConnectProfileConstants.PARAM_DEVICE_ID, "");
    builder.addParameter(DConnectProfileConstants.PARAM_SESSION_KEY, getClientId());
    builder.addParameter(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN, getAccessToken());
    try {
        HttpUriRequest request = new HttpPut(builder.toString());
        JSONObject root = sendRequest(request);
        assertResultError(ErrorCode.NOT_FOUND_DEVICE.getCode(), root);
    } catch (JSONException e) {
        fail("Exception in JSONObject." + e.getMessage());
    }
}

From source file:com.example.aab119.restclientexample.RestClient.java

public void execute(RequestMethod method) throws Exception {
    switch (method) {
    case GET: {//from  w ww.  j  ava 2s.co m
        HttpGet request = new HttpGet(url + addGetParams());
        request = (HttpGet) addHeaderParams(request);
        executeRequest(request, url);
        break;
    }
    case POST: {
        HttpPost request = new HttpPost(url);
        request = (HttpPost) addHeaderParams(request);
        request = (HttpPost) addBodyParams(request);
        executeRequest(request, url);
        break;
    }
    case PUT: {
        HttpPut request = new HttpPut(url);
        request = (HttpPut) addHeaderParams(request);
        request = (HttpPut) addBodyParams(request);
        executeRequest(request, url);
        break;
    }
    case DELETE: {
        HttpDelete request = new HttpDelete(url);
        request = (HttpDelete) addHeaderParams(request);
        executeRequest(request, url);
    }
    }
}

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

/**
 * Executes the task./*ww  w.j  a  v a2 s  . co 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.marklogic.client.test.util.TestServerBootstrapper.java

private void installBootstrapExtension() throws IOException {

    DefaultHttpClient client = new DefaultHttpClient();

    client.getCredentialsProvider().setCredentials(new AuthScope("localhost", port),
            new UsernamePasswordCredentials(username, password));

    HttpPut put = new HttpPut("http://" + host + ":" + port + "/v1/config/resources/bootstrap?method=POST");

    put.setEntity(new FileEntity(new File("src/test/resources/bootstrap.xqy"), "application/xquery"));
    HttpResponse response = client.execute(put);
    @SuppressWarnings("unused")
    HttpEntity entity = response.getEntity();
    System.out.println("Installed bootstrap extension.  Response is " + response.toString());

}

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 {/*w w w  .j  a  v  a2  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:org.jboss.pnc.auth.keycloakutil.util.HttpUtil.java

public static InputStream doPut(String url, String contentType, String acceptType, String content,
        String authorization) {// ww  w . ja v a 2  s  .c o  m
    try {
        return doPostOrPut(contentType, acceptType, content, authorization, new HttpPut(url));
    } catch (IOException e) {
        throw new RuntimeException("Failed to send request - " + e.getMessage(), e);
    }
}

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

/**
 * ??(?)??.//  w  ww  .  j av a  2  s  . c om
 * <pre>
 * ?HTTP
 * Method: PUT
 * Path: /phone/set?deviceid=xxxx&mode=0
 * </pre>
 * <pre>
 * ??
 * result?0???????
 * </pre>
 */
public void testPutSet001() {
    StringBuilder builder = new StringBuilder();
    builder.append(DCONNECT_MANAGER_URI);
    builder.append("/" + PhoneProfileConstants.PROFILE_NAME);
    builder.append("/" + PhoneProfileConstants.ATTRIBUTE_SET);
    builder.append("?");
    builder.append(DConnectProfileConstants.PARAM_DEVICE_ID + "=" + getDeviceId());
    builder.append("&");
    builder.append(PhoneProfileConstants.PARAM_MODE + "=0");
    builder.append("&");
    builder.append(AuthorizationProfileConstants.PARAM_ACCESS_TOKEN + "=" + getAccessToken());
    try {
        HttpUriRequest request = new HttpPut(builder.toString());
        JSONObject root = sendRequest(request);
        Assert.assertNotNull("root is null.", root);
        Assert.assertEquals(DConnectMessage.RESULT_OK, root.getInt(DConnectMessage.EXTRA_RESULT));
    } catch (JSONException e) {
        fail("Exception in JSONObject." + e.getMessage());
    }
}