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.forgerock.openam.mobile.commons.JSONRestRequest.java

/**
 * Inserts the supplied JSON data into the request
 *//*from   w ww .j a v  a  2 s .  c  o  m*/
public void insertData(JSONObject json) {

    if (json == null) {
        json = new JSONObject();
    }

    try {
        HttpPost request = getRequest();
        StringEntity entity = new StringEntity(json.toString(), HTTP.UTF_8);
        entity.setContentType(CONTENT_TYPE);
        request.setEntity(entity);
    } catch (UnsupportedEncodingException e) {
        fail(TAG, "Unable to set entity");
    }
}

From source file:io.github.jonestimd.neo4j.client.http.ApacheHttpDriver.java

public HttpResponse post(String uri, String jsonEntity) throws IOException {
    HttpPost post = new HttpPost(uri);
    StringEntity entity = new StringEntity(jsonEntity);
    entity.setContentType(ContentType.APPLICATION_JSON.toString());
    post.setEntity(entity);// ww  w  .ja v  a2  s  . co m
    return new ResponseAdapter(client.execute(post, clientContext));
}

From source file:org.apache.camel.component.cxf.jaxrs.CxfRsConvertBodyToTest.java

@Test
public void testPutConsumer() throws Exception {
    MockEndpoint mock = getMockEndpoint("mock:result");
    mock.expectedMessageCount(1);//  w ww  . j a  v  a  2s  . c  o  m
    mock.message(0).body().isInstanceOf(Customer.class);

    HttpPut put = new HttpPut("http://localhost:" + CXT + "/rest/customerservice/customers");
    StringEntity entity = new StringEntity(PUT_REQUEST, "ISO-8859-1");
    entity.setContentType("text/xml; charset=ISO-8859-1");
    put.addHeader("test", "header1;header2");
    put.setEntity(entity);
    HttpClient httpclient = new DefaultHttpClient();

    try {
        HttpResponse response = httpclient.execute(put);
        assertEquals(200, response.getStatusLine().getStatusCode());
        assertEquals("", EntityUtils.toString(response.getEntity()));
    } finally {
        httpclient.getConnectionManager().shutdown();
    }
}

From source file:br.ufg.inf.horus.implementation.service.HttpRequest.java

/**
 * Mtodo que executa o POST./* w w  w .j  a  v  a  2  s . co m*/
 *
 * @see HttpInterface
 * @param url Url para a requisio.
 * @param body Mensagem da requisio.
 * @param log Objeto para exibio de mensagens Log (opcional).
 * @return Resposta da requisio.
 */
@Override
public String request(String url, String body, Log log) throws BsusException {

    BsusValidator.verifyNull(body, " body", log);
    BsusValidator.verifyNull(url, " url", log);

    String resposta = "";

    try {
        CloseableHttpClient httpclient = HttpClientBuilder.create().build();
        StringEntity strEntity = new StringEntity(body, "UTF-8");
        strEntity.setContentType("text/xml");
        HttpPost post = new HttpPost(url);
        post.setEntity(strEntity);

        HttpResponse response = httpclient.execute(post);
        HttpEntity respEntity = response.getEntity();
        resposta = EntityUtils.toString(respEntity);

    } catch (IOException e) {
        String message = "Houve um erro ao abrir o documento .xml";
        BsusValidator.catchException(e, message, log);
    } catch (UnsupportedCharsetException e) {
        String message = "O charset 'UTF-8' da mensagem no esta sendo suportado.";
        BsusValidator.catchException(e, message, log);
    } catch (ParseException e) {
        String message = "Houve um erro ao buscar as informaes.";
        BsusValidator.catchException(e, message, log);
    }

    return resposta;
}

From source file:com.obomprogramador.dropbackend.TestLogin.java

private int sendRequest(String sentity) {
    int resultCode = -1;
    try {/*w  w  w.j  a  va 2s.c o  m*/
        HttpHost target = new HttpHost("localhost", 8080, "http");
        HttpPost postRequest = new HttpPost("/api/login");

        StringEntity input = new StringEntity(sentity);
        input.setContentType("application/json");
        postRequest.setEntity(input);

        logger.debug("### executing request to " + target);

        HttpResponse httpResponse = httpclient.execute(target, postRequest);
        HttpEntity entity = httpResponse.getEntity();

        logger.debug("### ----------------------------------------");
        logger.debug("### " + httpResponse.getStatusLine());
        Header[] headers = httpResponse.getAllHeaders();
        for (int i = 0; i < headers.length; i++) {
            logger.debug("### " + headers[i]);
        }
        logger.debug("### ----------------------------------------");

        if (entity != null) {
            logger.debug("### " + EntityUtils.toString(entity));
            resultCode = httpResponse.getStatusLine().getStatusCode();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return resultCode;
}

From source file:cat.calidos.morfeu.api.APITezt.java

protected InputStream postToRemote(String location, String content) throws Exception {

    String uri = webappPrefix + location;
    System.err.println("Posting to remote '" + uri + "'");
    URI u = new URI(uri);
    HttpPost request = new HttpPost(u);
    StringEntity params = new StringEntity(content, Config.DEFAULT_CHARSET);
    params.setContentType("application/json");
    request.setEntity(params);/*from  www  .  ja  va2s.  co m*/

    return client.execute(request).getEntity().getContent();

}

From source file:org.wso2.apim.billing.clients.DASRestClient.java

/**
 * Do a post request to the DAS REST// w  w  w  .  j  av a  2 s .  com
 *
 * @param request lucene json request
 * @param url     DAS rest api location
 * @return return the HttpResponse after the request sent
 * @throws IOException throw if the connection exception occur
 */
public CloseableHttpResponse doPost(SearchRequestBean request, String url) throws IOException {
    String json = gson.toJson(request);
    System.out.println(json);
    if (log.isDebugEnabled()) {
        log.debug("Sending Lucene Query : " + json);
    }
    HttpPost postRequest = new HttpPost(url);
    HttpContext context = HttpClientContext.create();

    //get the encoded basic authentication
    String cred = encodeCredentials(this.user, this.pass);
    postRequest.addHeader(HTTP_AUTH_HEADER_NAME, HTTP_AUTH_HEADER_TYPE + ' ' + cred);
    StringEntity input = new StringEntity(json);
    input.setContentType(APPLICATION_JSON);
    postRequest.setEntity(input);

    //send the request
    return httpClient.execute(postRequest, context);
}

From source file:service.StatisticsServerTest.java

public void testApp() throws UnsupportedEncodingException {
    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost("http://194.28.132.219:8080/statsserver_archive/rest/");
    StringEntity entity = new StringEntity("{\"age\":\"38\",\"sex\":\"Male\",\"country\":\"Russia\"}");
    entity.setContentType("application/json");
    post.setEntity(entity);//  w w  w .ja  v  a2  s.c  o m
    try {
        HttpResponse response = client.execute(post);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        String line = "";
        while ((line = rd.readLine()) != null) {
            System.out.println(line);
        }
    } catch (IOException e) {
        logger.error(e.getMessage());
    }
}

From source file:com.cloudant.client.internal.views.ViewMultipleRequester.java

public List<ViewResponse<K, V>> getViewResponses() throws IOException {
    //build the queries array of data to POST
    JsonArray queries = new JsonArray();
    ViewQueryParameters<K, V> viewQueryParameters = null;
    for (ViewQueryParameters<K, V> params : requestParameters) {
        if (viewQueryParameters == null) {
            viewQueryParameters = params;
        }//from  w ww  . j  av a2 s  . c  o  m
        queries.add(params.asJson());
    }
    JsonObject queryJson = new JsonObject();
    queryJson.add("queries", queries);
    //construct and execute the POST request
    HttpPost post = new HttpPost(viewQueryParameters.getViewURIBuilder().buildEncoded());
    StringEntity entity = new StringEntity(queryJson.toString(), "UTF-8");
    entity.setContentType("application/json");
    post.setEntity(entity);
    JsonObject jsonResponse = ViewRequester.executeRequestWithResponseAsJson(viewQueryParameters, post);
    //loop the returned array creating the ViewResponse objects
    List<ViewResponse<K, V>> responses = new ArrayList<ViewResponse<K, V>>();
    JsonArray jsonResponses = jsonResponse.getAsJsonArray("results");
    if (jsonResponses != null) {
        int index = 0;
        for (ViewQueryParameters<K, V> params : requestParameters) {
            JsonObject response = jsonResponses.get(index).getAsJsonObject();
            responses.add(new ViewResponseImpl<K, V>(params, response));
            index++;
        }
        return responses;
    } else {
        return Collections.emptyList();
    }
}

From source file:net.java.sip.communicator.service.httputil.HttpUtils.java

/**
 * Posting form to <tt>address</tt>. For submission we use POST method
 * which is "application/x-www-form-urlencoded" encoded.
 * @param httpClient the http client//from w w w .  j a  va2  s.co m
 * @param postMethod the post method
 * @param address HTTP address.
 * @param formParamNames the parameter names to include in post.
 * @param formParamValues the corresponding parameter values to use.
 * @param usernameParamIx the index of the username parameter in the
 * <tt>formParamNames</tt> and <tt>formParamValues</tt>
 * if any, otherwise -1.
 * @param passwordParamIx the index of the password parameter in the
 * <tt>formParamNames</tt> and <tt>formParamValues</tt>
 * if any, otherwise -1.
 * @param headerParamNames additional header name to include
 * @param headerParamValues corresponding header value to include
 * @return the result or null if send was not possible or
 * credentials ask if any was canceled.
 */
private static HttpEntity postForm(DefaultHttpClient httpClient, HttpPost postMethod, String address,
        ArrayList<String> formParamNames, ArrayList<String> formParamValues, int usernameParamIx,
        int passwordParamIx, RedirectHandler redirectHandler, List<String> headerParamNames,
        List<String> headerParamValues) throws Throwable {
    // if we have username and password in the parameters, lets
    // retrieve their values
    // if there are already filled skip asking the user
    Credentials creds = null;
    if (usernameParamIx != -1 && usernameParamIx < formParamNames.size() && passwordParamIx != -1
            && passwordParamIx < formParamNames.size()
            && (formParamValues.get(usernameParamIx) == null
                    || formParamValues.get(usernameParamIx).length() == 0)
            && (formParamValues.get(passwordParamIx) == null
                    || formParamValues.get(passwordParamIx).length() == 0)) {
        URL url = new URL(address);
        HTTPCredentialsProvider prov = (HTTPCredentialsProvider) httpClient.getCredentialsProvider();

        // don't allow empty username
        while (creds == null || creds.getUserPrincipal() == null
                || StringUtils.isNullOrEmpty(creds.getUserPrincipal().getName())) {
            creds = prov.getCredentials(new AuthScope(url.getHost(), url.getPort()));

            // it was user canceled lets stop processing
            if (creds == null && !prov.retry()) {
                return null;
            }
        }
    }

    // construct the name value pairs we will be sending
    List<NameValuePair> parameters = new ArrayList<NameValuePair>();
    // there can be no params
    if (formParamNames != null) {
        for (int i = 0; i < formParamNames.size(); i++) {
            // we are on the username index, insert retrieved username value
            if (i == usernameParamIx && creds != null) {
                parameters
                        .add(new BasicNameValuePair(formParamNames.get(i), creds.getUserPrincipal().getName()));
            } // we are on the password index, insert retrieved password val
            else if (i == passwordParamIx && creds != null) {
                parameters.add(new BasicNameValuePair(formParamNames.get(i), creds.getPassword()));
            } else // common name value pair, all info is present
            {
                parameters.add(new BasicNameValuePair(formParamNames.get(i), formParamValues.get(i)));
            }
        }
    }

    // our custom strategy, will check redirect handler should we redirect
    // if missing will use the default handler
    httpClient.setRedirectStrategy(new CustomRedirectStrategy(redirectHandler, parameters));

    // Uses String UTF-8 to keep compatible with android version and
    // older versions of the http client libs, as the one used
    // in debian (4.1.x)
    String s = URLEncodedUtils.format(parameters, "UTF-8");
    StringEntity entity = new StringEntity(s, "UTF-8");
    // set content type to "application/x-www-form-urlencoded"
    entity.setContentType(URLEncodedUtils.CONTENT_TYPE);

    // insert post values encoded.
    postMethod.setEntity(entity);

    if (headerParamNames != null) {
        for (int i = 0; i < headerParamNames.size(); i++) {
            postMethod.addHeader(headerParamNames.get(i), headerParamValues.get(i));
        }
    }

    // execute post
    return executeMethod(httpClient, postMethod, redirectHandler, parameters);
}