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.cloudhopper.sxmp.SxmpSender.java

static public Response send(String url, Request request, boolean shouldParseResponse)
        throws UnsupportedEncodingException, SxmpErrorException, IOException, SxmpParsingException,
        SAXException, ParserConfigurationException {
    // convert request into xml
    String requestXml = SxmpWriter.createString(request);
    String responseXml = null;//from  w w  w.  j av  a2 s .  co  m

    HttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    client.getParams().setParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, Boolean.FALSE);

    long start = System.currentTimeMillis();
    long stop = 0;

    logger.debug("Request XML:\n" + requestXml);

    // execute request
    try {
        HttpPost post = new HttpPost(url);
        StringEntity entity = new StringEntity(requestXml);
        // write old or new encoding?
        if (request.getVersion().equals(SxmpParser.VERSION_1_1)) {
            // v1.1 is utf-8
            entity.setContentType("text/xml; charset=\"utf-8\"");
        } else {
            // v1.0 was 8859-1, though that's technically wrong
            // unspecified XML must be encoded in UTF-8
            // maintained this way for backward compatibility
            entity.setContentType("text/xml; charset=\"iso-8859-1\"");
        }
        post.setEntity(entity);

        ResponseHandler<String> responseHandler = new BasicResponseHandler();

        // execute request (will throw exception if fails)
        responseXml = client.execute(post, responseHandler);

        stop = System.currentTimeMillis();
    } finally {
        // clean up all resources
        client.getConnectionManager().shutdown();
    }

    logger.debug("Response XML:\n" + responseXml);
    logger.debug("Response Time: " + (stop - start) + " ms");

    // deliver responses sometimes aren't parseable since its acceptable
    // for delivery responses to merely return "OK" and an HTTP 200 error
    if (!shouldParseResponse) {
        return null;
    } else {
        // convert response xml into an object
        SxmpParser parser = new SxmpParser(SxmpParser.VERSION_1_0);
        // v1.0 data remains in ISO-8859-1, and responses are v1.0
        ByteArrayInputStream bais = new ByteArrayInputStream(responseXml.getBytes("ISO-8859-1"));
        Operation op = parser.parse(bais);

        if (!(op instanceof Response)) {
            throw new SxmpErrorException(SxmpErrorCode.OPTYPE_MISMATCH,
                    "Unexpected response class type parsed");
        }

        return (Response) op;
    }
}

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);//  w w w  .  ja  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:su.fmi.photoshareclient.remote.LoginHandler.java

public static boolean register(String username, char[] password) {
    try {/*from  w ww .  ja v a 2s .c  o  m*/
        Random randomGenerator = new Random();
        ProjectProperties properties = new ProjectProperties();
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(
                "http://" + properties.get("socket") + properties.get("restEndpoint") + "/user/create");
        StringEntity input = new StringEntity("{\"firstName\":\"desktopUser\",\"lastName\":\"desktopUserLast\","
                + "\"username\": \"" + username + "\", \"email\": \"res" + randomGenerator.nextInt()
                + "@example.com\"," + "\"password\": \"" + new String(password) + "\"}");
        input.setContentType("application/json");
        post.setEntity(input);
        HttpResponse response = (HttpResponse) client.execute(post);
        return true;
        //                BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        //                String line = "";
        //                while ((line = rd.readLine()) != null) {
        //                    System.out.println(line);
        //                }
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(LoginGUI.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(LoginGUI.class.getName()).log(Level.SEVERE, null, ex);
    }
    return false;
}

From source file:co.aurasphere.botmill.telegram.internal.util.network.NetworkUtils.java

/**
 * Utility method that converts an object to its StringEntity
 * representation./*from   w  ww .  ja  va 2s . co  m*/
 * 
 * @param object
 *            the object to convert to a StringEntity.
 * @return a {@link StringEntity} object containing the object JSON.
 */
private static StringEntity toStringEntity(Object object) {
    StringEntity input = null;
    try {
        String json = JsonUtils.toJson(object);
        input = new StringEntity(json, "UTF-8");
        input.setContentType("application/json");
        logger.debug("Request: {}", inputStreamToString(input.getContent()));
    } catch (Exception e) {
        logger.error("Error during JSON message creation: ", e);
    }
    return input;
}

From source file:ecplugins.websphere.TestUtils.java

public static void setDefaultResourceAndWorkspace() throws Exception {

    if (!isResourceSetSuccessfully) {

        HttpClient httpClient = new DefaultHttpClient();
        JSONObject jo = new JSONObject();

        jo.put("projectName", "EC-WebSphere-" + StringConstants.PLUGIN_VERSION);
        jo.put("resourceName", StringConstants.RESOURCE_NAME);
        jo.put("workspaceName", StringConstants.WORKSPACE_NAME);

        HttpPut httpPutRequest = new HttpPut("http://" + props.getProperty(StringConstants.COMMANDER_USER) + ":"
                + props.getProperty(StringConstants.COMMANDER_PASSWORD) + "@" + StringConstants.COMMANDER_SERVER
                + ":8000/rest/v1.0/projects/" + "EC-WebSphere-" + StringConstants.PLUGIN_VERSION);

        StringEntity input = new StringEntity(jo.toString());

        input.setContentType("application/json");
        httpPutRequest.setEntity(input);
        HttpResponse httpResponse = httpClient.execute(httpPutRequest);

        if (httpResponse.getStatusLine().getStatusCode() >= 400) {
            throw new RuntimeException("Failed to set default resource  " + StringConstants.RESOURCE_NAME
                    + " to project " + "EC-WebSphere-" + StringConstants.PLUGIN_VERSION);
        }/*w w  w.  j a  v a 2  s.  c o  m*/
        System.out.println("Set the default resource as " + StringConstants.RESOURCE_NAME
                + " and default workspace as " + StringConstants.WORKSPACE_NAME + " successfully.");
        isResourceSetSuccessfully = true;
    }
}

From source file:ecplugins.websphere.TestUtils.java

/**
 *  Creates a new workspace. If the workspace already exists,It continues.
 *
 *//*from   ww w  . ja  v  a 2 s  .  c  om*/
static void createCommanderWorkspace() throws Exception {

    if (!isCommanderWorkspaceCreatedSuccessfully) {

        HttpClient httpClient = new DefaultHttpClient();
        JSONObject jo = new JSONObject();

        try {
            HttpPost httpPostRequest = new HttpPost(
                    "http://" + props.getProperty(StringConstants.COMMANDER_USER) + ":"
                            + props.getProperty(StringConstants.COMMANDER_PASSWORD) + "@"
                            + StringConstants.COMMANDER_SERVER + ":8000/rest/v1.0/workspaces/");

            jo.put("workspaceName", StringConstants.WORKSPACE_NAME);
            jo.put("description", "testAutomationWorkspace");
            jo.put("agentDrivePath", "C:/Program Files/Electric Cloud/ElectricCommander");
            jo.put("agentUncPath", "C:/Program Files/Electric Cloud/ElectricCommander");
            jo.put("agentUnixPath", "/opt/electriccloud/electriccommander");
            jo.put("local", true);

            StringEntity input = new StringEntity(jo.toString());

            input.setContentType("application/json");
            httpPostRequest.setEntity(input);
            HttpResponse httpResponse = httpClient.execute(httpPostRequest);

            if (httpResponse.getStatusLine().getStatusCode() == 409) {
                System.out.println("Commander workspace already exists.Continuing....");
            } else if (httpResponse.getStatusLine().getStatusCode() >= 400) {
                throw new RuntimeException(
                        "Failed to create commander workspace " + httpResponse.getStatusLine().getStatusCode()
                                + "-" + httpResponse.getStatusLine().getReasonPhrase());
            }
            // Indicate successful creating of workspace
            isCommanderWorkspaceCreatedSuccessfully = true;

        } finally {
            httpClient.getConnectionManager().shutdown();
        }
    }

}

From source file:ecplugins.websphere.TestUtils.java

/**
 *
 * @return//  w  ww .  j a  v  a 2 s . c  o m
 */
static void createCommanderResource() throws Exception {

    if (!isCommanderResourceCreatedSuccessfully) { // If CommanderResource not created before

        HttpClient httpClient = new DefaultHttpClient();
        JSONObject jo = new JSONObject();

        try {
            HttpPost httpPostRequest = new HttpPost(
                    "http://" + props.getProperty(StringConstants.COMMANDER_USER) + ":"
                            + props.getProperty(StringConstants.COMMANDER_PASSWORD) + "@"
                            + StringConstants.COMMANDER_SERVER + ":8000/rest/v1.0/resources/");

            jo.put("resourceName", StringConstants.RESOURCE_NAME);
            jo.put("description", "Resource created for test automation");
            jo.put("hostName", props.getProperty(StringConstants.WEBSPHERE_AGENT_IP));
            jo.put("port", props.getProperty(StringConstants.WEBSPHERE_AGENT_PORT));
            jo.put("workspaceName", StringConstants.WORKSPACE_NAME);
            jo.put("pools", "default");
            jo.put("local", true);

            StringEntity input = new StringEntity(jo.toString());

            input.setContentType("application/json");
            httpPostRequest.setEntity(input);
            HttpResponse httpResponse = httpClient.execute(httpPostRequest);

            if (httpResponse.getStatusLine().getStatusCode() == 409) {
                System.out.println("Commander resource already exists.Continuing....");

            } else if (httpResponse.getStatusLine().getStatusCode() >= 400) {
                throw new RuntimeException(
                        "Failed to create commander workspace " + httpResponse.getStatusLine().getStatusCode()
                                + "-" + httpResponse.getStatusLine().getReasonPhrase());
            }
            // Indicate successful creation commander resource.
            isCommanderResourceCreatedSuccessfully = true;
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
    }
}

From source file:com.jkoolcloud.tnt4j.streams.inputs.RestStream.java

/**
 * Performs JAX-RS service call over HTTP POST method request.
 *
 * @param uriStr/*from   www.j  av a  2  s . co m*/
 *            JAX-RS service URI
 * @param reqData
 *            request data
 * @param username
 *            user name used to perform request if service authentication is needed, or {@code null} if no
 *            authentication
 * @param password
 *            password used to perform request if service authentication is needed, or {@code null} if no
 *            authentication
 *
 * @return service response string
 * @throws Exception
 *             if exception occurs while performing JAX-RS service call
 */
protected static String executePOST(String uriStr, String reqData, String username, String password)
        throws Exception {
    if (StringUtils.isEmpty(uriStr)) {
        LOGGER.log(OpLevel.DEBUG, StreamsResources.getString(WsStreamConstants.RESOURCE_BUNDLE_NAME,
                "RestStream.cant.execute.post.request"), uriStr);
        return null;
    }

    if (StringUtils.isEmpty(reqData)) {
        return executeGET(uriStr, username, password);
    }

    LOGGER.log(OpLevel.DEBUG, StreamsResources.getString(WsStreamConstants.RESOURCE_BUNDLE_NAME,
            "RestStream.invoking.post.request"), uriStr, reqData);

    String respStr = null;
    CloseableHttpClient client = HttpClients.createDefault();
    try {
        HttpPost post = new HttpPost(uriStr);
        StringEntity reqEntity = new StringEntity(reqData == null ? "" : reqData);
        // here instead of JSON you can also have XML
        reqEntity.setContentType("application/json"); // NON-NLS

        // List<BasicNameValuePair> nameValuePairs = new
        // ArrayList<BasicNameValuePair>(1);
        // nameValuePairs.add(new BasicNameValuePair("name", "value"));
        // // you can have as many name value pair as you want in the list.
        // post.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        post.setEntity(reqEntity);

        respStr = executeRequest(client, post, username, password);
    } finally {
        Utils.close(client);
    }

    return respStr;
}

From source file:com.wst.cls.HTTPBaseIO.java

/**
 * String to HttpEntity(/*from w  w w  . j a v a2 s  .com*/
 *
 * @param nvps
 * @param charset HTTP.UTF_8
 * @return
 * @throws UnsupportedEncodingException
 */
public static HttpEntity StringToHttpEntity(String nvps, String charset) throws UnsupportedEncodingException {
    HttpEntity result = null;
    if (nvps != null) {
        StringEntity reqEntity = new StringEntity(nvps, charset);
        reqEntity.setContentType("application/x-www-form-urlencoded");
        result = reqEntity;
    }
    return result;
}

From source file:password.pwm.http.servlet.oauth.OAuthMachine.java

private static RestResults makeHttpRequest(final PwmRequest pwmRequest, final String debugText,
        final OAuthSettings settings, final String requestUrl, final Map<String, String> requestParams)
        throws IOException, PwmUnrecoverableException {
    final Date startTime = new Date();
    final String requestBody = PwmURL.appendAndEncodeUrlParameters("", requestParams);
    LOGGER.trace(pwmRequest,/*from ww w.j a v  a  2s . c  om*/
            "beginning " + debugText + " request to " + requestUrl + ", body: \n" + requestBody);
    final HttpPost httpPost = new HttpPost(requestUrl);
    httpPost.setHeader(PwmConstants.HttpHeader.Authorization.getHttpName(),
            new BasicAuthInfo(settings.getClientID(), settings.getSecret()).toAuthHeader());
    final StringEntity bodyEntity = new StringEntity(requestBody);
    bodyEntity.setContentType(PwmConstants.ContentTypeValue.form.getHeaderValue());
    httpPost.setEntity(bodyEntity);

    final X509Certificate[] certs = settings.getCertificates();

    final HttpResponse httpResponse;
    final String bodyResponse;
    try {
        if (certs == null || certs.length == 0) {
            httpResponse = PwmHttpClient.getHttpClient(pwmRequest.getConfig()).execute(httpPost);
        } else {
            httpResponse = PwmHttpClient
                    .getHttpClient(pwmRequest.getConfig(),
                            new PwmHttpClientConfiguration.Builder().setCertificate(certs).create())
                    .execute(httpPost);
        }
        bodyResponse = EntityUtils.toString(httpResponse.getEntity());
    } catch (PwmException | IOException e) {
        final String errorMsg;
        if (e instanceof PwmException) {
            errorMsg = "error during " + debugText + " http request to oauth server, remote error: "
                    + ((PwmException) e).getErrorInformation().toDebugStr();
        } else {
            errorMsg = "io error during " + debugText + " http request to oauth server: " + e.getMessage();
        }
        throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_OAUTH_ERROR, errorMsg));
    }

    final StringBuilder debugOutput = new StringBuilder();
    debugOutput.append(debugText).append(" ").append(TimeDuration.fromCurrent(startTime).asCompactString())
            .append(", status: ").append(httpResponse.getStatusLine()).append("\n");
    for (final Header responseHeader : httpResponse.getAllHeaders()) {
        debugOutput.append(" response header: ").append(responseHeader.getName()).append(": ")
                .append(responseHeader.getValue()).append("\n");
    }

    debugOutput.append(" body:\n ").append(bodyResponse);
    LOGGER.trace(pwmRequest, debugOutput.toString());

    if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
        throw new PwmUnrecoverableException(new ErrorInformation(PwmError.ERROR_OAUTH_ERROR,
                "unexpected HTTP status code (" + httpResponse.getStatusLine().getStatusCode() + ") during "
                        + debugText + " request to " + requestUrl));
    }

    return new RestResults(httpResponse, bodyResponse);
}