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:org.oss.bonita.utils.bonita.RestClient.java

protected HttpResponse executePutRequest(String apiURI, String payloadAsString) {
    try {/*from   ww  w. ja v  a2 s .  com*/
        HttpPut putRequest = new HttpPut(bonitaURI + apiURI);
        putRequest.addHeader("Content-Type", "application/json");

        StringEntity input = new StringEntity(payloadAsString);
        input.setContentType("application/json");
        putRequest.setEntity(input);

        return httpClient.execute(putRequest, httpContext);

    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

From source file:org.n52.oxf.ses.adapter.client.SESConnectorImpl.java

public SESResponse sendHttpPostRequest(String request, String action)
        throws IllegalStateException, IOException {
    if (!this.ready)
        return null;

    HttpPost req = new HttpPost(this.host.toString());

    String str;//from www . j  a  v  a 2  s .c om
    if (this.addSoap) {
        String thisPre = SOAP_PRE.replace("${ses_host}", req.getURI().toString()).replace("${soap_action}",
                action);
        str = XML_PRE + System.getProperty("line.separator") + thisPre + request + SOAP_POST;
    } else {
        str = XML_PRE + System.getProperty("line.separator") + request;
    }

    StringEntity postContent = new StringEntity(str);
    postContent.setContentType("text/xml; charset=utf-8");

    req.setEntity(postContent);

    HttpResponse response = null;
    try {
        response = this.httpClient.execute(req);
    } catch (Exception e) {
        logger.warn(e.getMessage());
        req.abort();
        return new SESResponse(500, null);
    }

    HttpEntity entity = response.getEntity();

    if (entity != null) {
        InputStream instream = entity.getContent();

        XmlObject xo = null;
        if (response.getStatusLine().getStatusCode() >= HttpStatus.SC_MULTIPLE_CHOICES) {
            logger.warn(parseError(instream));
        } else {
            try {
                xo = XmlObject.Factory.parse(instream);
            } catch (XmlException e) {
                logger.warn(e.getMessage(), e);
            }
            instream.close();
        }

        return new SESResponse(response.getStatusLine().getStatusCode(), xo);
    } else {
        req.abort();
        return new SESResponse(response.getStatusLine().getStatusCode(), null);
    }
}

From source file:org.oss.bonita.utils.bonita.RestClient.java

protected HttpResponse executePostRequest(String apiURI, String payloadAsString) {
    try {/*from  w  w  w  . j  a v  a 2  s .co m*/
        HttpPost postRequest = new HttpPost(bonitaURI + apiURI);

        StringEntity input = new StringEntity(payloadAsString);
        input.setContentType("application/json");

        postRequest.setEntity(input);

        HttpResponse response = httpClient.execute(postRequest, httpContext);

        return response;

    } catch (Exception e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
}

From source file:org.eoc.sdk.Dispatcher.java

private boolean doPost(URL url, JSONObject json) {
    if (url == null || json == null)
        return false;

    String jsonBody = json.toString();
    try {/* w  ww . j ava 2s .c o  m*/
        HttpPost post = new HttpPost(url.toURI());
        StringEntity se = new StringEntity(jsonBody);
        se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        post.setEntity(se);

        return doRequest(post);
    } catch (URISyntaxException e) {
        Logy.w(LOGGER_TAG, String.format("URI Syntax Error %s", url.toString()), e);
    } catch (UnsupportedEncodingException e) {
        Logy.w(LOGGER_TAG, String.format("Unsupported Encoding %s", jsonBody), e);
    }
    return false;
}

From source file:BusinessLogic.Controller.RestController.java

public Plan updatePlan(Plan plan) throws Exception {
    StringBuilder responseS = new StringBuilder();

    try {/*from  w  ww  .  jav  a2 s .c o  m*/

        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpPost postRequest = new HttpPost("http://locahost/JoyCenter/resources/plans/" + plan.getId());

        Gson gson = new Gson();
        StringEntity input = new StringEntity(gson.toJson(plan));
        input.setContentType("application/json");
        postRequest.setEntity(input);

        HttpResponse response = httpClient.execute(postRequest);

        if (response.getStatusLine().getStatusCode() != 201) {
            throw new RuntimeException(
                    "Failed : HTTP error code : " + response.getStatusLine().getStatusCode());
        }

        BufferedReader br = new BufferedReader(new InputStreamReader((response.getEntity().getContent())));

        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            responseS.append(output);
        }

        httpClient.getConnectionManager().shutdown();

    } catch (MalformedURLException e) {

        e.printStackTrace();

    } catch (IOException e) {

        e.printStackTrace();

    }

    Gson gson = new Gson();
    return gson.fromJson(responseS.toString(), Plan.class);

}

From source file:eu.musesproject.client.connectionmanager.HttpConnectionsHelper.java

/**
 * Http post implementation //  www  .j  a  v  a 2 s .  c  om
 * @param url
 * @param data
 * @return httpResponse
 * @throws ClientProtocolException
 * @throws IOException
 */

public synchronized HttpResponse doPost(String type, String url, String data)
        throws ClientProtocolException, IOException {
    HttpResponse httpResponse = null;
    HttpPost httpPost = new HttpPost(url);
    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, TIMEOUT);
    DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);
    StringEntity s = new StringEntity(data.toString());
    s.setContentEncoding("UTF-8");
    s.setContentType("application/xml");
    httpPost.addHeader("connection-type", type);
    httpPost.setEntity(s);
    httpPost.addHeader("accept", "application/xml");
    if (cookie == null || cookie.isExpired(new Date())) {
        try {
            httpResponse = httpclient.execute(httpPost);
            List<Cookie> cookies = httpclient.getCookieStore().getCookies();
            if (cookies.isEmpty()) {
                Log.d(TAG, "None");
            } else {
                cookie = cookies.get(0);
                cookieExpiryDate = cookie.getExpiryDate();
                Log.d(TAG, "Curent cookie expiry : " + cookieExpiryDate);
            }
        } catch (ClientProtocolException e) {
            Log.d(TAG, e.getMessage());
        } catch (Exception e) {
            Log.d(TAG, e.getMessage());
        }

    } else {
        httpPost.addHeader("accept", "application/xml");
        httpclient.getCookieStore().addCookie(cookie);
        try {
            httpResponse = httpclient.execute(httpPost);
        } catch (ClientProtocolException e) {
            Log.d(TAG, e.getMessage());
        } catch (Exception e) {
            Log.d(TAG, e.getMessage());
        }
    }
    return httpResponse;
}

From source file:com.ea.core.bridge.ws.rest.client.AbstractRestClient.java

protected HttpEntity getHttpEntity(Object... params) throws Exception {
    if (params != null) {
        DynamicDTO jsonObject = null;/* w  w  w .java2 s .c o  m*/
        for (Object obj : params) {
            if (obj instanceof DynamicDTO) {
                jsonObject = (DynamicDTO) obj;
                break;
            }
        }
        if (jsonObject != null) {
            String jsonString = JsonUtil.generatorJson(jsonObject.getBean());
            StringEntity entity = new StringEntity(jsonString, "UTF-8");
            entity.setContentType(ContentType.APPLICATION_JSON.toString());
            return entity;
        }
    }
    return null;
}

From source file:org.opendaylight.eman.impl.EmanSNMPBinding.java

public String setEoAttrSNMP(String deviceIP, String attribute, String value) {
    /* To do: generalize targetURL */
    String targetUrl = "http://localhost:8181/restconf/operations/snmp:snmp-set";
    String bodyString = buildSNMPSetBody(deviceIP, attribute, value);
    CloseableHttpClient httpClient = HttpClients.createDefault();
    String result = null;/*from   w  ww .j av  a  2  s . c  o m*/

    LOG.info("EmanSNMPBinding.setEoAttrSNMP: HTTP SET SNMP call to: " + targetUrl);

    try {
        HttpPost httpPost = new HttpPost(targetUrl);
        httpPost.addHeader("Authorization", "Basic " + encodedAuthStr);

        StringEntity inputBody = new StringEntity(bodyString);
        inputBody.setContentType(CONTENTTYPE_JSON);
        httpPost.setEntity(inputBody);

        CloseableHttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity responseEntity = httpResponse.getEntity();
        LOG.info("Response Status: " + httpResponse.getStatusLine().toString());
        InputStream in = responseEntity.getContent();

    } catch (Exception ex) {
        LOG.info("Error: " + ex.getMessage(), ex);
    } finally {
        try {
            httpClient.close();
        } catch (IOException ex) {
            LOG.info("Error: " + ex.getMessage(), ex);
        }
    }
    return (result);
}

From source file:com.wegas.integration.IntegrationTest.java

public void login() throws IOException {
    HttpPost post = new HttpPost(baseURL + "/rest/User/Authenticate");
    String content = "{\"@class\" : \"AuthenticationInformation\"," + "\"login\": \"root@root.com\","
            + "\"password\": \"1234\"," + "\"remember\": \"true\"" + "}";

    StringEntity strEntity = new StringEntity(content);
    strEntity.setContentType("application/json");
    post.setEntity(strEntity);//from www  .  jav a2  s.c  o  m

    HttpResponse loginResponse = client.execute(post);

    Assert.assertEquals(HttpStatus.SC_OK, loginResponse.getStatusLine().getStatusCode());

    Header[] headers = loginResponse.getHeaders("Set-Cookie");
    if (headers.length > 0) {
        cookie = headers[0].getValue();
    }
}