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:eu.trentorise.smartcampus.protocolcarrier.Communicator.java

private static HttpRequestBase buildRequest(MessageRequest msgRequest, String appToken, String authToken)
        throws URISyntaxException, UnsupportedEncodingException {
    String host = msgRequest.getTargetHost();
    if (host == null)
        throw new URISyntaxException(host, "null URI");
    if (!host.endsWith("/"))
        host += '/';
    String address = msgRequest.getTargetAddress();
    if (address == null)
        address = "";
    if (address.startsWith("/"))
        address = address.substring(1);//  ww w .j  a v a 2  s  .c o m
    String uriString = host + address;
    try {
        URL url = new URL(uriString);
        URI uri = new URI(url.getProtocol(), url.getUserInfo(), url.getHost(), url.getPort(), url.getPath(),
                url.getQuery(), url.getRef());
        uriString = uri.toURL().toString();
    } catch (MalformedURLException e) {
        throw new URISyntaxException(uriString, e.getMessage());
    }
    if (msgRequest.getQuery() != null)
        uriString += "?" + msgRequest.getQuery();

    //      new URI(uriString);

    HttpRequestBase request = null;
    if (msgRequest.getMethod().equals(Method.POST)) {
        HttpPost post = new HttpPost(uriString);
        HttpEntity httpEntity = null;
        if (msgRequest.getRequestParams() != null) {
            // if body and requestparams are either not null there is an
            // exception
            if (msgRequest.getBody() != null && msgRequest != null) {
                throw new IllegalArgumentException("body and requestParams cannot be either populated");
            }
            httpEntity = new MultipartEntity();

            for (RequestParam param : msgRequest.getRequestParams()) {
                if (param.getParamName() == null || param.getParamName().trim().length() == 0) {
                    throw new IllegalArgumentException("paramName cannot be null or empty");
                }
                if (param instanceof FileRequestParam) {
                    FileRequestParam fileparam = (FileRequestParam) param;
                    ((MultipartEntity) httpEntity).addPart(param.getParamName(), new ByteArrayBody(
                            fileparam.getContent(), fileparam.getContentType(), fileparam.getFilename()));
                }
                if (param instanceof ObjectRequestParam) {
                    ObjectRequestParam objectparam = (ObjectRequestParam) param;
                    ((MultipartEntity) httpEntity).addPart(param.getParamName(),
                            new StringBody(convertObject(objectparam.getVars())));
                }
            }
            // mpe.addPart("file",
            // new ByteArrayBody(msgRequest.getFileContent(), ""));
            // post.setEntity(mpe);
        }
        if (msgRequest.getBody() != null) {
            httpEntity = new StringEntity(msgRequest.getBody(), Constants.CHARSET);
            ((StringEntity) httpEntity).setContentType(msgRequest.getContentType());
        }
        post.setEntity(httpEntity);
        request = post;
    } else if (msgRequest.getMethod().equals(Method.PUT)) {
        HttpPut put = new HttpPut(uriString);
        if (msgRequest.getBody() != null) {
            StringEntity se = new StringEntity(msgRequest.getBody(), Constants.CHARSET);
            se.setContentType(msgRequest.getContentType());
            put.setEntity(se);
        }
        request = put;
    } else if (msgRequest.getMethod().equals(Method.DELETE)) {
        request = new HttpDelete(uriString);
    } else {
        // default: GET
        request = new HttpGet(uriString);
    }

    Map<String, String> headers = new HashMap<String, String>();

    // default headers
    if (appToken != null) {
        headers.put(RequestHeader.APP_TOKEN.toString(), appToken);
    }
    if (authToken != null) {
        // is here for compatibility
        headers.put(RequestHeader.AUTH_TOKEN.toString(), authToken);
        headers.put(RequestHeader.AUTHORIZATION.toString(), "Bearer " + authToken);
    }
    headers.put(RequestHeader.ACCEPT.toString(), msgRequest.getContentType());

    if (msgRequest.getCustomHeaders() != null) {
        headers.putAll(msgRequest.getCustomHeaders());
    }

    for (String key : headers.keySet()) {
        request.addHeader(key, headers.get(key));
    }

    return request;
}

From source file:com.investoday.code.util.aliyun.api.gateway.util.HttpUtil.java

/**
 * HTTP PUT//from  ww w  .j a  va  2  s .com
 *
 * @param url                  http://host+path+query
 * @param headers              Http
 * @param bytes                
 * @param appKey               APP KEY
 * @param appSecret            APP
 * @param timeout              
 * @param signHeaderPrefixList ???Header?
 * @return 
 * @throws Exception
 */
public static HttpResponse httpPut(String url, Map<String, String> headers, byte[] bytes, String appKey,
        String appSecret, int timeout, List<String> signHeaderPrefixList) throws Exception {
    headers = initialBasicHeader(headers, appKey, appSecret, HttpMethod.PUT, url, null, signHeaderPrefixList);
    HttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(timeout));

    HttpPut put = new HttpPut(url);
    for (Map.Entry<String, String> e : headers.entrySet()) {
        put.addHeader(e.getKey(), e.getValue());
    }

    if (bytes != null) {
        put.setEntity(new ByteArrayEntity(bytes));

    }

    return httpClient.execute(put);
}

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));
    }//  www .  ja va  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:com.example.aliyundemo.ocr.util.HttpUtil.java

/**
 * HTTP PUT//ww  w . j  ava  2s .c  o  m
 *
 * @param url                  http://host+path+query
 * @param headers              Http
 * @param bytes                
 * @param appKey               APP KEY
 * @param appSecret            APP
 * @param timeout              
 * @param signHeaderPrefixList ???Header?
 * @return 
 * @throws Exception
 */
public static HttpResponse httpPut(String url, Map<String, String> headers, byte[] bytes, String appKey,
        String appSecret, int timeout, List<String> signHeaderPrefixList) throws Exception {
    headers = initialBasicHeader(headers, appKey, appSecret, HttpMethod.PUT, url, null, signHeaderPrefixList);
    HttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(timeout));

    HttpPut put = new HttpPut(url);
    for (Map.Entry<String, String> e : headers.entrySet()) {
        put.addHeader(e.getKey(), MessageDigestUtil.utf8ToIso88591(e.getValue()));
    }

    if (bytes != null) {
        put.setEntity(new ByteArrayEntity(bytes));

    }

    return httpClient.execute(put);
}

From source file:com.investoday.code.util.aliyun.api.gateway.util.HttpUtil.java

/**
 * HTTP PUT //from w ww  .j  a v a2s. c o m
 *
 * @param url                  http://host+path+query
 * @param headers              Http
 * @param body                 
 * @param appKey               APP KEY
 * @param appSecret            APP
 * @param timeout              
 * @param signHeaderPrefixList ???Header?
 * @return 
 * @throws Exception
 */
public static HttpResponse httpPut(String url, Map<String, String> headers, String body, String appKey,
        String appSecret, int timeout, List<String> signHeaderPrefixList) throws Exception {
    headers = initialBasicHeader(headers, appKey, appSecret, HttpMethod.PUT, url, null, signHeaderPrefixList);
    HttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(timeout));

    HttpPut put = new HttpPut(url);
    for (Map.Entry<String, String> e : headers.entrySet()) {
        put.addHeader(e.getKey(), e.getValue());
    }

    if (StringUtils.isNotBlank(body)) {
        put.setEntity(new StringEntity(body, Constants.ENCODING));

    }

    return httpClient.execute(put);
}

From source file:com.example.aliyundemo.ocr.util.HttpUtil.java

/**
 * HTTP PUT // w w  w .  j  a va  2s  . c  o m
 *
 * @param url                  http://host+path+query
 * @param headers              Http
 * @param body                 
 * @param appKey               APP KEY
 * @param appSecret            APP
 * @param timeout              
 * @param signHeaderPrefixList ???Header?
 * @return 
 * @throws Exception
 */
public static HttpResponse httpPut(String url, Map<String, String> headers, String body, String appKey,
        String appSecret, int timeout, List<String> signHeaderPrefixList) throws Exception {
    headers = initialBasicHeader(headers, appKey, appSecret, HttpMethod.PUT, url, null, signHeaderPrefixList);
    HttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, getTimeout(timeout));

    HttpPut put = new HttpPut(url);
    for (Map.Entry<String, String> e : headers.entrySet()) {
        put.addHeader(e.getKey(), MessageDigestUtil.utf8ToIso88591(e.getValue()));
    }

    if (StringUtils.isNotBlank(body)) {
        put.setEntity(new StringEntity(body, Constants.ENCODING));

    }

    return httpClient.execute(put);
}

From source file:com.hoccer.tools.HttpHelper.java

public static HttpResponse putFile(String pUri, File pFile, String pContentType, String pAccept)
        throws IOException, HttpClientException, HttpServerException {
    HttpPut put = new HttpPut(pUri);
    FileEntity entity = new FileEntity(pFile, pContentType);
    put.setEntity(entity);
    put.addHeader("Content-Type", pContentType);
    put.addHeader("Accept", pAccept);
    return executeHTTPMethod(put, PUT_TIMEOUT);
}

From source file:com.thed.zapi.cloud.sample.FetchExecuteUpdate.java

public static String updateExecutions(String uriStr, ZFJCloudRestClient client, String accessKey,
        StringEntity executionJSON) throws URISyntaxException, JSONException, ParseException, IOException {

    URI uri = new URI(uriStr);
    int expirationInSec = 360;
    JwtGenerator jwtGenerator = client.getJwtGenerator();
    String jwt = jwtGenerator.generateJWT("PUT", uri, expirationInSec);
    // System.out.println(uri.toString());
    // System.out.println(jwt);

    HttpResponse response = null;/*from ww w  .  ja  v a2 s. com*/
    HttpClient restClient = new DefaultHttpClient();

    HttpPut executeTest = new HttpPut(uri);
    executeTest.addHeader("Content-Type", "application/json");
    executeTest.addHeader("Authorization", jwt);
    executeTest.addHeader("zapiAccessKey", accessKey);
    executeTest.setEntity(executionJSON);

    try {
        response = restClient.execute(executeTest);
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    int statusCode = response.getStatusLine().getStatusCode();
    // System.out.println(statusCode);
    String executionStatus = "No Test Executed";
    // System.out.println(response.toString());
    HttpEntity entity = response.getEntity();

    if (statusCode >= 200 && statusCode < 300) {
        String string = null;
        try {
            string = EntityUtils.toString(entity);
            JSONObject executionResponseObj = new JSONObject(string);
            JSONObject descriptionResponseObj = executionResponseObj.getJSONObject("execution");
            JSONObject statusResponseObj = descriptionResponseObj.getJSONObject("status");
            executionStatus = statusResponseObj.getString("description");
            System.out.println(executionResponseObj.get("issueKey") + "--" + executionStatus);
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    } else {

        try {
            String string = null;
            string = EntityUtils.toString(entity);
            JSONObject executionResponseObj = new JSONObject(string);
            cycleId = executionResponseObj.getString("clientMessage");
            // System.out.println(executionResponseObj.toString());
            throw new ClientProtocolException("Unexpected response status: " + statusCode);

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        }
    }
    return executionStatus;
}

From source file:net.ravendb.client.RavenDBAwareTests.java

protected static void startServer(int port, boolean deleteData) {
    HttpPut put = null;
    try {//from  w  w  w .j a  v  a  2s .c  o  m
        String putUrl = DEFAULT_SERVER_RUNNER_URL;
        if (deleteData) {
            putUrl += "?deleteData=true";
        }
        put = new HttpPut(putUrl);
        put.setEntity(new StringEntity(getCreateServerDocument(port), ContentType.APPLICATION_JSON));
        HttpResponse httpResponse = client.execute(put);
        if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            throw new IllegalStateException(
                    "Invalid response on put:" + httpResponse.getStatusLine().getStatusCode()
                            + IOUtils.toString(httpResponse.getEntity().getContent()));
        }
    } catch (IOException e) {
        throw new IllegalStateException(e);
    } finally {
        if (put != null) {
            put.releaseConnection();
        }
    }
}

From source file:com.evrythng.java.wrapper.util.FileUtils.java

/**
 * Uploads a {@code File} with PRIVATE read access.
 *
 * @param uri upload {@link URI}//from   w w w .j av  a2  s  . c  om
 * @param contentTypeString content type
 * @param contentFile the file to upload
 * @throws IOException
 */
public static void uploadPrivateContent(final URI uri, final String contentTypeString, final File contentFile)
        throws IOException {

    LOGGER.info("uploadPrivateContent START: uri: [{}]; content type: [{}], content file: [{}]",
            new Object[] { uri, contentTypeString, contentFile });

    CloseableHttpClient closeableHttpClient = HttpClients.createDefault();

    HttpPut httpPut = new HttpPut(uri);
    httpPut.addHeader(HttpHeaders.CONTENT_TYPE, contentTypeString);
    httpPut.addHeader(FileUtils.X_AMZ_ACL_HEADER_NAME, FileUtils.X_AMZ_ACL_HEADER_VALUE_PRIVATE);

    ContentType contentType = ContentType.create(contentTypeString);
    FileEntity fileEntity = new FileEntity(contentFile, contentType);
    httpPut.setEntity(fileEntity);

    CloseableHttpResponse response = closeableHttpClient.execute(httpPut);
    StatusLine statusLine = response.getStatusLine();

    if (!(statusLine.getStatusCode() == HttpStatus.SC_OK)) {
        throw new IOException(String.format("An error occurred while trying to upload private file - %d: %s",
                statusLine.getStatusCode(), statusLine.getReasonPhrase()));
    }

    LOGGER.info("uploadPrivateContent END: uri: [{}]; content type: [{}], content file: [{}]",
            new Object[] { uri, contentTypeString, contentFile });
}