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:org.janusgraph.diskstorage.es.ElasticSearchIndexTest.java

@BeforeClass
public static void startElasticsearch() throws Exception {
    esr = new ElasticsearchRunner();
    esr.start();//from   ww w  .  j a  v  a 2s.  co m
    httpClient = HttpClients.createDefault();
    objectMapper = new ObjectMapper();
    host = new HttpHost(InetAddress.getByName(esr.getHostname()), ElasticsearchRunner.PORT);
    if (esr.getEsMajorVersion().value > 2) {
        IOUtils.closeQuietly(httpClient.execute(host, new HttpDelete("_ingest/pipeline/pipeline_1")));
        final HttpPut newPipeline = new HttpPut("_ingest/pipeline/pipeline_1");
        newPipeline.setHeader("Content-Type", "application/json");
        newPipeline.setEntity(
                new StringEntity("{\"description\":\"Test pipeline\",\"processors\":[{\"set\":{\"field\":\""
                        + STRING + "\",\"value\":\"hello\"}}]}", Charset.forName("UTF-8")));
        IOUtils.closeQuietly(httpClient.execute(host, newPipeline));
    }
}

From source file:com.lhings.java.http.WebServiceCom.java

private static void executePut(String apikey, String url, String requestBody)
        throws IOException, LhingsException {
    HttpPut putRequest = new HttpPut(url);
    putRequest.setHeader("Content-Type", "application/json");
    HttpEntity entity = new StringEntity(requestBody, Charset.forName("utf-8"));
    putRequest.setEntity(entity);
    putRequest.setHeader("X-Api-Key", apikey);
    HttpResponse response = executeRequest(putRequest);
    String json = response.getResponseBody();
    int status = response.getStatusCode();
    if (status == LHINGS_ERROR_HTTP_STATUS) {
        int lhingsErrorCode = new JSONObject(json).getInt("responseStatus");
        String errorMessage = new JSONObject(json).getString("message");
        switch (lhingsErrorCode) {
        case LHINGS_V1_API_BAD_REQUEST_ERROR_CODE:
            throw new BadRequestException("Lhings API error. HTTP status " + status + ". Lhings error code "
                    + lhingsErrorCode + " - " + errorMessage);
        case LHINGS_V1_API_UNAUTHORIZED_ERROR_CODE:
            throw new UnauthorizedException("Lhings API error. HTTP status " + status + ". Lhings error code "
                    + lhingsErrorCode + " - " + errorMessage);
        case LHINGS_V1_API_NOT_FOUND_ERROR_CODE:
            throw new DeviceDoesNotExistException("Lhings API error. HTTP status " + status
                    + ". Lhings error code " + lhingsErrorCode + " - " + errorMessage);
        default:/*from ww w.j a  v  a2 s  .  co  m*/
            throw new LhingsException("Lhings API error. HTTP status " + status + ". Lhings error code "
                    + lhingsErrorCode + " - " + errorMessage);
        }
    } else if (status != 200 && status != 201) {
        // HTTP error
        throw new LhingsException("HTTP error. Code: " + status + " - " + response.getStatusMessage());
    }
}

From source file:tech.beshu.ror.integration.FieldLevelSecurityTests.java

private static void insertDoc(String docName, RestClient restClient, String idx, String field) {
    if (adminClient == null) {
        adminClient = restClient;/*from ww  w. j av a2  s .c  o  m*/
    }

    String path = "/" + IDX_PREFIX + idx + "/documents/doc-" + docName + String.valueOf(Math.random());
    try {

        HttpPut request = new HttpPut(restClient.from(path));
        request.setHeader("Content-Type", "application/json");
        request.setHeader("refresh", "true");
        request.setHeader("timeout", "50s");

        String body = "{\"" + field + "\": \"" + docName + "\", \"dummy2\": true}";
        System.out.println("inserting: " + body);
        request.setEntity(new StringEntity(body));
        System.out.println(body(restClient.execute(request)));

    } catch (Exception e) {
        e.printStackTrace();
        throw new IllegalStateException("Test problem", e);
    }

    // Polling phase.. #TODO is there a better way?
    try {
        Thread.sleep(5000);

        HttpResponse response;
        do {
            HttpHead request = new HttpHead(restClient.from(path));
            request.setHeader("x-api-key", "p");
            response = restClient.execute(request);
            System.out.println(
                    "polling for " + docName + ".. result: " + response.getStatusLine().getReasonPhrase());
            Thread.sleep(200);
        } while (response.getStatusLine().getStatusCode() != 200);
    } catch (Exception e) {
        e.printStackTrace();
        throw new IllegalStateException("Cannot configure test case", e);
    }

}

From source file:myexamples.dbase.MyHelpMethods.java

public static String sendHttpRequest2(String url, String requestBody, String requestType) throws IOException {
    String result = null;/*w  ww.ja  va2 s.c  o  m*/
    CloseableHttpClient httpclient = HttpClients.createDefault();
    CloseableHttpResponse httpResponse;
    try {
        switch (requestType) {
        case "Get":
            httpResponse = httpclient.execute(new HttpGet(url));
            break;
        case "Post":
            HttpPost httppost = new HttpPost(url);
            if (requestBody != null)
                httppost.setEntity(new StringEntity(requestBody));
            httpResponse = httpclient.execute(httppost);
            break;
        case "Put":
            HttpPut httpPut = new HttpPut(url);
            httpPut.addHeader("Content-Type", "application/json");
            httpPut.addHeader("Accept", "application/json");
            if (requestBody != null)
                httpPut.setEntity(new StringEntity(requestBody, DEFAULT_CHARSET));
            httpResponse = httpclient.execute(httpPut);
            break;
        case "Delete":
            httpResponse = httpclient.execute(new HttpDelete(url));
            break;
        default:
            httpResponse = httpclient.execute(new HttpGet(url));
            break;
        }
        try {
            HttpEntity entity1 = httpResponse.getEntity();
            if (entity1 != null) {
                long len = entity1.getContentLength();
                if (len != -1 && len < MAX_CONTENT_LENGTH) {
                    result = EntityUtils.toString(entity1, DEFAULT_CHARSET);
                } else {
                    System.out.println("Error!!!! entity length=" + len);
                }
            }
            EntityUtils.consume(entity1);
        } finally {
            httpResponse.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        httpclient.close();
    }
    return result;
}

From source file:com.ninehcom.userinfo.util.HttpUtils.java

/**
 * Put String//  w  ww .  j  a v a 2  s.  c o  m
 * @param host
 * @param path
 * @param method
 * @param headers
 * @param querys
 * @param body
 * @return
 * @throws Exception
 */
public static HttpResponse doPut(String host, String path, String method, Map<String, String> headers,
        Map<String, String> querys, String body) throws Exception {
    HttpClient httpClient = wrapClient(host);

    HttpPut request = new HttpPut(buildUrl(host, path, querys));
    for (Map.Entry<String, String> e : headers.entrySet()) {
        request.addHeader(e.getKey(), e.getValue());
    }

    if (StringUtils.isNotBlank(body)) {
        request.setEntity(new StringEntity(body, "utf-8"));
    }

    return httpClient.execute(request);
}

From source file:com.upyun.sdk.utils.HttpClientUtils.java

private static HttpResponse put(String url, HttpClient httpclient, Map<String, String> headers,
        InputStream instream, Integer length) {
    HttpPut httpPut = new HttpPut(url);
    HttpResponse response = null;/*from  ww w. j a  v a2 s  .  c om*/
    if (headers != null) {
        for (String key : headers.keySet()) {
            httpPut.addHeader(key, headers.get(key));
        }
    }

    InputStreamEntity ise = new InputStreamEntity(instream, length);
    httpPut.setEntity(ise);

    httpclient.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);// 
    httpclient.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT, SO_TIMEOUT); // ?

    try {
        response = httpclient.execute(httpPut);
    } catch (Exception e) {
        LogUtil.exception(logger, e);
    }

    return response;
}

From source file:com.bjorsond.android.timeline.sync.ServerUploader.java

/**
 * Sends a JSON-string to the Google App Engine Server. This runs async in a separate thread.
 * /*from www .j  a  v  a 2  s.co m*/
 * @param jsonString Content of HTTP request, as JSON.
 * @param targetHost The host of the server
 * @param httpPut The HTTP PUT request.
 */
private static void sendJSONTOGAEServer(final String jsonString, final HttpHost targetHost,
        final HttpPut httpPut) {
    Runnable sendRunnable = new Runnable() {

        public void run() {
            try {
                DefaultHttpClient httpClient = new DefaultHttpClient();

                StringEntity entity = new StringEntity(jsonString, "UTF-8");
                httpPut.setEntity(entity);

                // execute is a blocking call, it's best to call this code in a thread separate from the ui's
                HttpResponse response = httpClient.execute(targetHost, httpPut);

                Log.v("Put to GAE", response.getStatusLine().toString());
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
    };

    Thread thread = new Thread(null, sendRunnable, "putToGAE");
    thread.start();

}

From source file:com.daskiworks.ghwatch.backend.RemoteSystemClient.java

public static Response<String> putToURL(Context context, GHCredentials apiCredentials, String url,
        Map<String, String> headers, String content) throws NoRouteToHostException, URISyntaxException,
        IOException, ClientProtocolException, AuthenticationException {
    if (!Utils.isInternetConnectionAvailable(context))
        throw new NoRouteToHostException("Network not available");

    URI uri = new URI(url);
    DefaultHttpClient httpClient = prepareHttpClient(uri, apiCredentials);

    HttpPut httpPut = new HttpPut(uri);

    setHeaders(httpPut, headers);/*from   w w w .j av  a  2 s  .  c om*/

    if (content != null)
        httpPut.setEntity(new StringEntity(content, "UTF-8"));

    // create response object here to measure request duration
    Response<String> ret = new Response<String>();
    ret.requestStartTime = System.currentTimeMillis();

    HttpResponse httpResponse = httpClient.execute(httpPut);

    parseResponseHeaders(context, httpResponse, ret);

    processStandardHttpResponseCodes(httpResponse);

    ret.data = getResponseContentAsString(httpResponse);

    ret.snapRequestDuration();
    writeReponseInfo(ret, context);
    return ret;
}

From source file:no.norrs.projects.andronary.service.utils.HttpUtil.java

public static HttpResponse PUT(String uri, List<NameValuePair> data) throws IOException {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPut httpPost = new HttpPut(uri);
    //httpPost.addHeader("Accept", "application/json");
    httpPost.addHeader("Content-Type", "application/json; charset=utf-8");
    httpPost.addHeader("User-Agent", "Andronary/0.1");
    httpPost.addHeader("Connection", "close");
    StringEntity e = new StringEntity(data.get(0).getValue(), HTTP.UTF_8);
    //httpPost.setEntity(new UrlEncodedFormEntity(data));
    httpPost.setEntity(e);
    HttpResponse response;//from   w  w  w.jav a2 s  .  co  m

    return httpClient.execute(httpPost);
    //return response.getStatusLine().getStatusCode();
    /*HttpEntity entity = response.getEntity();
    return entity.getContent();*/

}

From source file:org.megam.api.http.TransportMachinery.java

public static TransportResponse put(TransportTools nuts) throws ClientProtocolException, IOException {

    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpPut httpput = new HttpPut(nuts.urlString());

    if (nuts.headers() != null) {
        for (Map.Entry<String, String> headerEntry : nuts.headers().entrySet()) {
            httpput.addHeader(headerEntry.getKey(), headerEntry.getValue());
        }/*  w  ww .j  a v  a 2s .  c o m*/
    }

    if (nuts.pairs() != null && (nuts.contentType() == null)) {
        httpput.setEntity(new UrlEncodedFormEntity(nuts.pairs()));
    }

    if (nuts.contentType() != null) {
        httpput.setEntity(new StringEntity(nuts.contentString(), nuts.contentType()));
    }

    TransportResponse transportResp = null;
    try {
        HttpResponse httpResp = httpclient.execute(httpput);
        transportResp = new TransportResponse(httpResp.getStatusLine(), httpResp.getEntity(),
                httpResp.getLocale());
    } finally {
        httpput.releaseConnection();
    }
    return transportResp;

}