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:monitor.console.control.HTTPRequest.java

public HTTPRequest(String login, byte[] password, FindUrl url)
        throws UnsupportedEncodingException, IOException {

    HttpClient client = new DefaultHttpClient();
    System.out.println(url.getHostName() + ":" + url.getPortNumber() + "/" + url.getRestServiceName());
    HttpPost post = new HttpPost(
            url.getHostName() + ":" + url.getPortNumber() + "/" + url.getRestServiceName());
    StringEntity input = new StringEntity(
            "{\"login\":" + "\"" + login + "\",\"password\":\"" + Arrays.toString(password) + "\"}");
    input.setContentType("application/json");
    post.setEntity(input);/*from w ww .  j a v  a2  s  .com*/
    HttpResponse response = client.execute(post);
    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    String tmp = "";
    while ((tmp = rd.readLine()) != null) {
        resp = tmp.replaceAll("\"", "");
        System.out.println(resp);
    }
}

From source file:org.hydracache.server.httpd.handler.HttpGetMethodHandler.java

private StringEntity generateStringEntityForXmlData(Data data)
        throws IOException, UnsupportedEncodingException {
    DataMessage dataMsg = new DataMessage(data);

    StringWriter out = new StringWriter();
    messageEncoder.encodeXml(dataMsg, out);

    StringEntity stringEntity = new StringEntity(out.toString());
    stringEntity.setContentType(XML_TEXT_RESPONSE_CONTENT_TYPE);
    return stringEntity;
}

From source file:com.fun.util.HttpClientUtil.java

/**
 * url??Jsonpost?//from  www.  ja v a  2s  . co  m
 *
 * @param url
 * @param jsonData
 * @return
 */
public String post(String url, String jsonData) {
    String content = null;
    try {
        HttpPost post = new HttpPost(url);
        StringEntity entity = new StringEntity(jsonData, Charset.forName("UTF-8"));
        entity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        post.setEntity(entity);
        HttpResponse response = this.client.execute(post);
        content = EntityUtils.toString(response.getEntity());
    } catch (Exception e) {
        HttpClientUtil.logger.error(String.format("post [%s] happens error ", url), e);
    }
    return content;
}

From source file:com.cubeia.backoffice.wallet.service.IndexingPlugin.java

private void addTask(final Account tx) {
    exec.submit(new Runnable() {

        @Override/*from   w w w .j a v  a 2s  .co  m*/
        public void run() {
            log.debug("Indexing account " + tx.getId());
            DefaultHttpClient dhc = new DefaultHttpClient();
            HttpPut method = new HttpPut(baseUrl + tx.getId());
            method.addHeader(CONTENT_TYPE, APPLICATION_JSON);
            try {
                String json = mapper.writeValueAsString(tx);
                if (log.isTraceEnabled()) {
                    log.trace("Account " + tx.getId() + " JSON: " + json);
                }
                StringEntity ent = new StringEntity(json, "UTF-8");
                ent.setContentType(APPLICATION_JSON);
                method.setEntity(ent);
                HttpResponse resp = dhc.execute(method);
                if (!String.valueOf(resp.getStatusLine().getStatusCode()).startsWith("2")) {
                    log.warn("Failed to index account " + tx.getId() + "; Server responded with status: "
                            + resp.getStatusLine());
                } else {
                    HttpEntity entity = resp.getEntity();
                    String string = EntityUtils.toString(entity, "UTF-8");
                    if (log.isTraceEnabled()) {
                        log.trace("Account " + tx.getId() + " return JSON: " + string);
                    }
                    JsonNode node = mapper.readTree(string);
                    if (!node.get("ok").asBoolean()) {
                        log.warn("Failed to index account " + tx.getId() + "; Response JSON: " + string);
                    }
                }
            } catch (Exception e) {
                log.error("Failed to account transaction " + tx.getId(), e);
            }
        }
    });
}

From source file:org.wso2.carbon.identity.cloud.web.jaggery.clients.MutualSSLHttpClient.java

public String doPost(String endPoint, HttpHeaders headers, String jsonContent) {
    String responseString = null;
    try {/*ww w. j  a v a 2s  . c om*/
        StringEntity inputMappings = new StringEntity(jsonContent);
        inputMappings.setContentType(ApplicationJson);
        HttpPost postMethod = new HttpPost(endPoint);
        postMethod.setEntity(inputMappings);
        responseString = doHttpMethod(postMethod, headers);
    } catch (UnsupportedEncodingException e) {
        log.error("Error while creating payload for http request. Payload : " + jsonContent, e);
    }
    return responseString;
}

From source file:org.wso2.carbon.identity.cloud.web.jaggery.clients.MutualSSLHttpClient.java

public String doPut(String endPoint, HttpHeaders headers, String jsonContent) {
    String responseString = null;
    try {/* w  ww  .  ja  v  a  2  s  .c  o m*/
        StringEntity inputMappings = new StringEntity(jsonContent);
        inputMappings.setContentType(ApplicationJson);
        HttpPut putMethod = new HttpPut(endPoint);
        putMethod.setEntity(inputMappings);
        responseString = doHttpMethod(putMethod, headers);
    } catch (UnsupportedEncodingException e) {
        log.error("Error while creating payload for http request. Payload : " + jsonContent, e);
    }
    return responseString;
}

From source file:org.jboss.as.test.integration.management.http.XCorrelationIdTestCase.java

@Test
public void testPost() throws Exception {
    ModelNode op = Util.getReadAttributeOperation(PathAddress.EMPTY_ADDRESS, "server-state");
    HttpPost post = new HttpPost(url.toURI());

    String cmdStr = op.toJSONString(true);
    StringEntity entity = new StringEntity(cmdStr);
    entity.setContentType(APPLICATION_JSON);
    post.setEntity(entity);//from   w  w  w .  ja  v a  2s  .c  om

    assertNull(getCorrelationHeader(post));

    post.addHeader(HEADER, VALUE1);
    assertEquals(VALUE1, getCorrelationHeader(post));

    post.setHeader(HEADER, VALUE2);
    assertEquals(VALUE2, getCorrelationHeader(post));

    post.setHeader(HEADER, VALUE1);
    assertEquals(VALUE1, getCorrelationHeader(post));

    post.removeHeaders(HEADER);
    assertNull(getCorrelationHeader(post));
}

From source file:de.unidue.inf.is.ezdl.dlservices.library.manager.referencesystems.connotea.ConnoteaUtils.java

/** send a POST Request and return the response as string */
String sendPostRequest(String url, String bodytext) throws Exception {
    String sresponse;/*  w  w w  .j a v  a 2  s . com*/

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);

    // set authentication header
    httppost.addHeader("Authorization", authHeader);

    // very important. otherwise there comes a invalid request error
    httppost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);

    StringEntity body = new StringEntity(bodytext);
    body.setContentType("application/x-www-form-urlencoded");

    httppost.setEntity(body);

    HttpResponse response = httpclient.execute(httppost);

    // check status code.
    if (response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK
            || response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_CREATED
            || response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_NOT_FOUND) {
        // Not found too. no exception should be thrown.
        HttpEntity entity = response.getEntity();

        sresponse = readResponseStream(entity.getContent());
        httpclient.getConnectionManager().shutdown();
    } else {
        HttpEntity entity = response.getEntity();
        sresponse = readResponseStream(entity.getContent());
        String httpcode = Integer.toString(response.getStatusLine().getStatusCode());
        httpclient.getConnectionManager().shutdown();
        throw new ReferenceSystemException(httpcode, "Connotea Error", RDFUtils.parseError(sresponse));
    }
    return sresponse;

}

From source file:org.imsglobal.caliper.request.ApacheHttpRequestor.java

/**
 * Generate an HTTP StringEntity from the provided JSON string.  Set the ContentType to 'application/json'.
 * @param value//from   www . j a  v a  2s  .  c  om
 * @param contentType
 * @return
 * @throws UnsupportedEncodingException
 */
public StringEntity generatePayload(String value, ContentType contentType) throws UnsupportedEncodingException {
    StringEntity payload = new StringEntity(value);
    payload.setContentType(contentType.toString());

    return payload;
}

From source file:tk.jomp16.plugin.cyanogenmod.download.Download.java

public void download(CommandEvent commandEvent) throws IOException {
    if (commandEvent.getArgs().size() >= 1) {
        System.out.println(commandEvent.getArgs());

        DeviceInfo deviceInfo = Device.getDevices().get(commandEvent.getArgs().get(0));

        if (deviceInfo != null) {
            HttpPost httpPost = new HttpPost(CM_DOWNLOAD_API);
            StringEntity json = new StringEntity(gson.toJson(new CMApiRequest(deviceInfo.getCodename())));
            json.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            httpPost.setEntity(json);//  ww  w  .jav a  2 s  .c o m
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpContext context = new BasicHttpContext();
            HttpResponse response = httpClient.execute(httpPost, context);

            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                return;
            }

            DownloadInfo downloadInfo;

            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent()))) {
                downloadInfo = gson.fromJson(reader, DownloadInfo.class);
            }

            if (downloadInfo.result.size() > 0) {
                DownloadInfo.Result latest = downloadInfo.result.get(0);
                commandEvent.respond("Latest build (" + latest.channel + ") for " + deviceInfo.getCodename()
                        + ": " + latest.url + " [md5sum: " + latest.md5sum + "]");
            } else {
                commandEvent.respond("No builds for " + deviceInfo.getCodename());
            }
        }
    }
}