Example usage for org.apache.http.entity StringEntity setContentType

List of usage examples for org.apache.http.entity StringEntity setContentType

Introduction

In this page you can find the example usage for org.apache.http.entity StringEntity setContentType.

Prototype

public void setContentType(Header header) 

Source Link

Usage

From source file:com.globalsight.everest.workflowmanager.WfStatePostThread.java

private void doPost(WorkflowStatePosts wfStatePost, JSONObject message) {
    int num = wfStatePost.getRetryNumber();
    CloseableHttpClient httpClient = getHttpClient();
    for (int i = 0; i < num; i++) {
        try {/*  w ww. j  av  a2  s.c o m*/
            String listenerUrl = wfStatePost.getListenerURL();
            String secretKey = wfStatePost.getSecretKey();
            HttpPost httpPost = new HttpPost(listenerUrl);
            httpPost.setHeader(HttpHeaders.AUTHORIZATION, secretKey);
            RequestConfig config = RequestConfig.custom()
                    .setConnectionRequestTimeout(wfStatePost.getTimeoutPeriod() * 1000)
                    .setConnectTimeout(wfStatePost.getTimeoutPeriod() * 1000)
                    .setSocketTimeout(wfStatePost.getTimeoutPeriod() * 1000).build();
            httpPost.setConfig(config);
            StringEntity reqEntity = new StringEntity(message.toString());
            reqEntity.setContentEncoding("UTF-8");
            reqEntity.setContentType("application/json");
            httpPost.setEntity(reqEntity);
            HttpResponse response = null;
            try {
                response = httpClient.execute(httpPost);
            } catch (Exception e) {
                s_logger.error("Post workflow transition info error:", e);
            } finally {
                if (response != null) {
                    EntityUtils.consumeQuietly(response.getEntity());
                }
            }
            if (response != null) {
                int statusCode = response.getStatusLine().getStatusCode();
                if (statusCode == 204) {
                    break;
                } else {
                    logPostFailureInfo(statusCode);
                    if (StringUtils.isNotEmpty(wfStatePost.getNotifyEmail()) && (i == num)) {
                        String recipient = wfStatePost.getNotifyEmail();
                        long companyId = wfStatePost.getCompanyId();
                        String[] messageArguments = { wfStatePost.getName(), wfStatePost.getListenerURL(),
                                message.toString() };
                        ServerProxy.getMailer().sendMailFromAdmin(recipient, messageArguments,
                                MailerConstants.WORKFLOW_STATE_POST_FAILURE_SUBJECT,
                                MailerConstants.WORKFLOW_STATE_POST_FAILURE_MESSAGE, String.valueOf(companyId));
                    }
                }
            }
        } catch (Exception e) {
            s_logger.error(e);
        }
    }
}

From source file:edu.washington.iam.tools.WebClient.java

public Element doSoapRequest(String url, String action, String body) {

    closeIdleConnections();//from  w  w w .java  2s .  c  om

    // log.debug("do soap: " + action);
    Element ele = null;
    // DefaultHttpClient soapclient = new DefaultHttpClient((ClientConnectionManager)connectionManager, new BasicHttpParams());
    if (soapclient == null)
        soapclient = new DefaultHttpClient((ClientConnectionManager) connectionManager, new BasicHttpParams());
    // soapclient.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false); 

    try {

        // log.debug(" url: " + url);
        // log.debug("content: [" + soapHeader + body + soapTrailer + "]");

        HttpPost httppost = new HttpPost(url);
        httppost.addHeader("SOAPAction", action);

        StringEntity strent = new StringEntity(soapHeader + body + soapTrailer);
        strent.setContentType("text/xml; charset=utf-8");
        httppost.setEntity(strent);

        CloseableHttpResponse response = soapclient.execute(httppost);

        if (response.getStatusLine().getStatusCode() >= 400) {
            log.error("soap error: " + response.getStatusLine().getStatusCode() + " = "
                    + response.getStatusLine().getReasonPhrase());
            throw new WebClientException("soap error");
        }
        HttpEntity entity = response.getEntity();

        // null is error - should get something
        if (entity == null) {
            throw new WebClientException("soapclient post exception");
        }

        // log.debug("got " + entity.getContentLength() + " bytes");
        // parse response text
        Document doc = documentBuilder.parse(entity.getContent());

        ele = XMLHelper.getElementByName(doc.getDocumentElement(), "Body");
        if (ele == null) {
            log.error("no body element");
            throw new WebClientException("no body element?");
        }
    } catch (Exception e) {
        log.error("exception " + e);
    }
    return ele;
}

From source file:com.evolveum.polygon.scim.SalesforceHandlingStrategy.java

@Override
public Uid groupUpdateProcedure(Integer statusCode, JSONObject jsonObject, String uri, Header authHeader,
        ScimConnectorConfiguration conf) {

    Uid id = null;/*from   w  ww  . j a v  a2  s.  c om*/
    HttpClient httpClient = initHttpClient(conf);
    LOGGER.info(
            "Status code from first update query: {0}. Processing trough Salesforce \"group/member update\" workaround. ",
            statusCode);
    HttpGet httpGet = buildHttpGet(uri, authHeader);
    try (CloseableHttpResponse response = (CloseableHttpResponse) httpClient.execute(httpGet);) {
        statusCode = response.getStatusLine().getStatusCode();
        LOGGER.info("status code: {0}", statusCode);
        if (statusCode == 200) {

            String responseString = EntityUtils.toString(response.getEntity());
            if (!responseString.isEmpty()) {

                JSONObject json = new JSONObject(responseString);
                LOGGER.info("Json object returned from service provider: {0}", json);
                for (String attributeName : jsonObject.keySet()) {

                    json.put(attributeName, jsonObject.get(attributeName));
                }

                StringEntity bodyContent = new StringEntity(json.toString(1));
                bodyContent.setContentType(CONTENTTYPE);

                HttpPatch httpPatch = new HttpPatch(uri);
                httpPatch.addHeader(authHeader);
                httpPatch.addHeader(PRETTYPRINTHEADER);
                httpPatch.setEntity(bodyContent);

                try (CloseableHttpResponse secondaryResponse = (CloseableHttpResponse) httpClient
                        .execute(httpPatch)) {
                    responseString = EntityUtils.toString(secondaryResponse.getEntity());
                    statusCode = secondaryResponse.getStatusLine().getStatusCode();
                    LOGGER.info("status code: {0}", statusCode);
                    if (statusCode == 200 || statusCode == 201) {
                        LOGGER.info("Update of resource was successful");

                        json = new JSONObject(responseString);
                        id = new Uid(json.getString(ID));
                        LOGGER.ok("Json response: {0}", json.toString(1));
                        return id;
                    } else {
                        ErrorHandler.onNoSuccess(responseString, statusCode, "updating object");
                    }
                }
            }
        }

    } catch (ClientProtocolException e) {
        LOGGER.error(
                "An protocol exception has occurred while in the process of updating a resource object. Possible mismatch in the interpretation of the HTTP specification: {0}",
                e.getLocalizedMessage());
        LOGGER.info(
                "An protocol exception has occurred while in the process of updating a resource object. Possible mismatch in the interpretation of the HTTP specification: {0}",
                e);
        throw new ConnectionFailedException(
                "An protocol exception has occurred while in the process of updating a resource object, Possible mismatch in the interpretation of the HTTP specification.",
                e);
    } catch (IOException e) {

        StringBuilder errorBuilder = new StringBuilder(
                "Occurrence in the process of creating a resource object");

        if ((e instanceof SocketTimeoutException || e instanceof NoRouteToHostException)) {
            errorBuilder.insert(0, "The connection timed out. ");
            throw new OperationTimeoutException(errorBuilder.toString(), e);
        } else {

            LOGGER.error(
                    "An error has occurred while processing the http response. Occurrence in the process of updating a resource object: {0}",
                    e.getLocalizedMessage());
            LOGGER.info(
                    "An error has occurred while processing the http response. Occurrence in the process of creating a resource object: {0}",
                    e);

            throw new ConnectorIOException(errorBuilder.toString(), e);
        }
    }
    return id;
}

From source file:org.freeeed.data.index.SolrIndex.java

protected void sendPostCommand(String point, String param) throws SolrException {
    HttpClient httpClient = new DefaultHttpClient();

    try {/*from  w w w. ja  v  a  2  s. c om*/
        HttpPost request = new HttpPost(point);
        StringEntity params = new StringEntity(param, HTTP.UTF_8);
        params.setContentType("text/xml");

        request.setEntity(params);

        HttpResponse response = httpClient.execute(request);
        if (response.getStatusLine().getStatusCode() != 200) {
            logger.error("Solr Invalid Response: {}", response.getStatusLine().getStatusCode());
            logger.error(response.getStatusLine().toString());
            HttpEntity entity = response.getEntity();
            String responseString = EntityUtils.toString(entity, "UTF-8");
            logger.error(responseString);
            logger.error("point:");
            logger.error(point);
            logger.error("param");
            logger.error(param);
        }
    } catch (Exception ex) {
        logger.error("Problem sending request", ex);
    }
}

From source file:co.forsaken.api.json.JsonWebCall.java

public void execute(Object arg) {
    if (_log)/*from www .  j a v a  2s . c o  m*/
        System.out.println("Requested: [" + _url + "]");
    try {
        canConnect();
    } catch (Exception ex) {
        ex.printStackTrace();
        return;
    }
    HttpClient httpClient = new DefaultHttpClient(_connectionManager);
    try {
        Gson gson = new Gson();
        HttpPost request = new HttpPost(_url);
        if (arg != null) {
            StringEntity params = new StringEntity(gson.toJson(arg));
            params.setContentType(new BasicHeader("Content-Type", "application/json"));
            request.setEntity(params);
        }
        httpClient.execute(request);
    } catch (Exception ex) {
        System.out.println("JSONWebCall.executeNoRet() Error: \n" + ex.getMessage());
        StackTraceElement[] arrOfSTE;
        int max = (arrOfSTE = ex.getStackTrace()).length;
        for (int i = 0; i < max; i++) {
            StackTraceElement trace = arrOfSTE[i];
            System.out.println(trace);
        }
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
    if (_log)
        System.out.println("Returned: [" + _url + "]");
}

From source file:io.clh.lrt.androidservice.TraceListenerService.java

public HttpResponse postAPI(String path, String key, String jsonData) {
    try {/*from w  ww  . ja v  a 2 s.co m*/
        jsonData = jsonData.replace("\\\"", "\"");
        //         List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
        //            nameValuePairs.add(new BasicNameValuePair(key,
        //                jsonData));

        JSONObject data = new JSONObject();
        try {
            data.put(key, jsonData);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        StringEntity se = new StringEntity(jsonData.toString());
        se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));

        postMethod = new HttpPost("http://lrtserver.herokuapp.com/" + path);
        postMethod.setEntity(se);
        //            postMethod.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        return restClient.execute(postMethod);
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

From source file:com.ibm.dataworks.DataLoadResource.java

/**
 * Save an activity. Return JSON containing the activity ID.
 * /*from w w w . j a  v a2  s  .com*/
 * @param inputObj the input json object
 * 
 * @return the Response.
 */
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response saveActivity(JSONObject inputObj) {
    try {
        //
        // Step 1: Post the activity definition .../activities
        //
        HttpClient client = getAuthenticatedHttpClient();
        String activitiesUrl = vcapInfo.getDataLoadUrl() + "/activities";
        HttpPost postRequest = new HttpPost(activitiesUrl);
        StringEntity input = new StringEntity(inputObj.serialize());
        input.setContentType(MediaType.APPLICATION_JSON);
        postRequest.setEntity(input);
        postRequest.setHeader("Accept", MediaType.APPLICATION_JSON);
        //
        // Step 2: Get the response.
        //
        HttpResponse response = client.execute(postRequest);
        int status = response.getStatusLine().getStatusCode();
        // Check the status code and return an internal server error if it is not 200
        if (status != 200) {
            JSONObject errorObject = createErrorObject("SavingActivityFailed", response);
            return Response.status(status).entity(errorObject).build();
        }

        //
        // Step 3: return the result.
        //
        JSONObject activityResponse = JSONObject.parse(response.getEntity().getContent());
        return Response.status(status).entity(activityResponse).build();
    } catch (Exception exc) {
        JSONObject errorObject = createErrorObject(exc);
        return Response.status(Status.INTERNAL_SERVER_ERROR).entity(errorObject).build();
    }
}

From source file:groovyx.net.http.EncoderRegistry.java

/**
 * Helper method used by encoder methods to create an {@link HttpEntity}
 * instance that encapsulates the request data.  This may be used by any
 * non-streaming encoder that needs to send textual data.  It also sets the
 * {@link #setCharset(String) charset} portion of the content-type header.
 *
 * @param ct content-type of the data//from w  w w.ja  v a  2 s .c  o  m
 * @param data textual request data to be encoded
 * @return an instance to be used for the
 *  {@link HttpEntityEnclosingRequest#setEntity(HttpEntity) request content}
 * @throws UnsupportedEncodingException
 */
protected StringEntity createEntity(Object ct, String data) throws UnsupportedEncodingException {
    StringEntity entity = new StringEntity(data, charset.toString());
    entity.setContentType(ct.toString());
    return entity;
}

From source file:com.partnet.automation.http.ApacheHttpAdapter.java

private void setEntity(HttpEntityEnclosingRequestBase httpBase, String contentType, String body) {
    //TODO make charset configurable?
    if (body != null) {
        StringEntity entity = new StringEntity(body, Consts.UTF_8);

        if (contentType == null && body != null) {
            LOG.warn("Content type is not setup for request {} {}", httpBase.getMethod(), httpBase.getURI());
        }//from   w  w w. jav a 2  s. c o  m

        entity.setContentType(contentType);
        httpBase.setEntity(entity);

    }
}

From source file:srl.distributed.client.Client.java

public synchronized Response sendRequest(Request request) {
    setConnected(false);// w ww .ja v a2s  .  c om
    HttpPost post = new HttpPost(serverAddress.toString());
    HttpEntity responseEntity = null;
    Response message = null;
    ObjectMapper mapper = mapperProvider.getMapper();

    messageTiming.reset();

    try {
        if (messageTimingEnabled)
            messageTiming.startSerialization();

        String requestVal = mapper.writeValueAsString(request);

        if (messageTimingEnabled)
            messageTiming.endSerialization();

        if (messageLog != null) {
            messageLog.append("//REQUEST\n");
            messageLog.append(requestVal + "\n");
            messageLog.flush();
        }
        if (messageTimingEnabled)
            messageTiming.startTransmission();

        StringEntity entity = new StringEntity(requestVal);
        post.setEntity(entity);
        entity.setContentType("application/json");
        HttpResponse response;
        synchronized (httpClient) {
            response = httpClient.execute(post);
        }

        if (messageTimingEnabled)
            messageTiming.endTransmission();
        if (messageTimingEnabled)
            messageTiming.startDeserialization();
        responseEntity = response.getEntity();
        InputStream inStream = responseEntity.getContent();

        if (responseEntity.getContentType() != null) {
            if (messageLog == null)
                message = mapper.readValue(inStream, Response.class);
            else {
                String entityVal = EntityUtils.toString(responseEntity);
                messageLog.append("//RESPONSE\n");
                messageLog.append(entityVal + "\n");
                messageLog.flush();
                message = mapper.readValue(entityVal, Response.class);
            }
            inStream.close();
            setConnected(true);
        } else {
            throw new ClientException("Able to connect but response is not from Server. Incorrect URL?");
        }
    } catch (ClientException e) {
        e.printStackTrace();
        message = new ClientErrorResponse(e);
    } catch (Exception e) {
        e.printStackTrace();
        message = new ClientErrorResponse(e);
    } finally {
        try {
            if (responseEntity != null)
                responseEntity.consumeContent();
        } catch (IOException e) {
            message = new ClientErrorResponse(e);
        }
    }
    if (messageTimingEnabled)
        messageTiming.endDeserialization();
    return message;
}