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.urbanstew.soundcloudapi.test.RequestTest.java

public final void testPutMeWebsiteXML() throws Exception {
    StringEntity entity = new StringEntity("<user><website>http://website.example.com</website></user>");
    entity.setContentType("application/xml");

    HttpResponse response = mApi.put("/me", entity);
    assertEquals(200, response.getStatusLine().getStatusCode());
}

From source file:com.rackspacecloud.client.service_registry.clients.BaseClient.java

protected ClientResponse performRequestWithPayload(String path, List<NameValuePair> params,
        HttpEntityEnclosingRequestBase method, java.lang.Object payload, boolean parseAsJson, Type responseType,
        boolean reAuthenticate, int retryCount) throws Exception {
    String body;/*from   www  . j a  va  2s.c om*/
    int statusCode;

    this.authClient.refreshToken(reAuthenticate);

    method.setURI(new URI(this.apiUrl + "/" + this.authClient.getAuthToken().getTenant().get("id") + path));
    method.setHeader("User-Agent", Client.VERSION);
    method.setHeader("X-Auth-Token", this.authClient.getAuthToken().getId());

    Gson gson = new GsonBuilder().setPrettyPrinting().enableComplexMapKeySerialization().create();

    body = gson.toJson(payload);
    StringEntity input = new StringEntity(body);
    input.setContentType("application/json");

    method.setEntity(input);

    HttpResponse response = this.client.execute(method);
    statusCode = response.getStatusLine().getStatusCode();

    if ((statusCode == 401) && (retryCount < MAX_401_RETRIES)) {
        retryCount++;
        logger.info("API server returned 401, re-authenticating and re-trying the request");
        return this.performRequestWithPayload(path, params, method, payload, parseAsJson, responseType, true,
                retryCount);
    }

    return new ClientResponse(response, parseAsJson, responseType);
}

From source file:org.wso2.carbon.apimgt.usage.client.DASRestClient.java

/**
 * Do a post request to the DAS REST/*www.  j a  v  a2  s.  c o  m*/
 *
 * @param json 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
 */
CloseableHttpResponse post(String json, String url) throws IOException {
    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 = RestClientUtil.encodeCredentials(this.user, this.pass);
    postRequest.addHeader(APIUsageStatisticsClientConstants.HTTP_AUTH_HEADER_NAME,
            APIUsageStatisticsClientConstants.HTTP_AUTH_HEADER_TYPE + ' ' + cred);
    StringEntity input = new StringEntity(json);
    input.setContentType(APIUsageStatisticsClientConstants.APPLICATION_JSON);
    postRequest.setEntity(input);

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

From source file:com.brightcove.zartan.encode.ZencodeAPI.java

private JsonNode encodeFile(TranscodeInfo transcode, URI transcodeApiUrl, ZencoderCredentials zc) {

    HttpPost method = new HttpPost(transcodeApiUrl);
    BasicHeader keyHeader = new BasicHeader("Zencoder-Api-Key", zc.getApiKey());

    method.addHeader(keyHeader);//w w  w  .j av  a 2  s .com

    String json = getJson(transcode);
    System.out.println(json);

    StringEntity entity;
    try {
        entity = new StringEntity(json);

        entity.setContentType("application/json");

        method.setEntity(entity);

        HttpResponse response = null;
        DefaultHttpClient httpAgent = new DefaultHttpClient();

        response = httpAgent.execute(method);

        // Make sure the HTTP communication was OK (not the same as an error in the Media API
        // reponse)
        Integer statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != 201) {
            httpAgent.getConnectionManager().shutdown();
            // TODO:throw inteligent failure
            return null;
        }

        // Parse the response
        HttpEntity resentity = response.getEntity();
        JsonNode jsonObj = getJSONFromEntity(resentity);
        httpAgent.getConnectionManager().shutdown();
        return jsonObj;
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;

}

From source file:com.gitblit.plugin.flowdock.FlowDock.java

/**
 * Send a payload message.//  w w w .  j  a  v  a 2 s  .  c o  m
 *
 * @param payload
 * @throws IOException
 */
public void send(Payload payload) throws IOException {

    String flow = payload.getFlow();
    String token;

    if (StringUtils.isEmpty(flow)) {
        // default flow
        token = runtimeManager.getSettings().getString(Plugin.SETTING_DEFAULT_TOKEN, null);
    } else {
        // specified flow, validate token
        token = runtimeManager.getSettings().getString(String.format(Plugin.SETTING_FLOW_TOKEN, flow), null);
        if (StringUtils.isEmpty(token)) {
            token = runtimeManager.getSettings().getString(Plugin.SETTING_DEFAULT_TOKEN, null);
            log.warn("No FlowDock API token specified for '{}', defaulting to default flow'",
                    payload.getFlow());
            log.warn("Please set '{} = TOKEN' in gitblit.properties",
                    String.format(Plugin.SETTING_FLOW_TOKEN, flow));
        }
    }

    Gson gson = new GsonBuilder().registerTypeAdapter(Date.class, new GmtDateTypeAdapter()).create();
    String json = gson.toJson(payload);
    log.debug(json);

    HttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(AllClientPNames.CONNECTION_TIMEOUT, 5000);
    client.getParams().setParameter(AllClientPNames.SO_TIMEOUT, 5000);

    String flowdockUrl = payload.getEndPoint(token);
    HttpPost post = new HttpPost(flowdockUrl);
    post.getParams().setParameter(CoreProtocolPNames.USER_AGENT, Constants.NAME + "/" + Constants.getVersion());
    post.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");

    if (payload.postForm()) {
        // post as a form with a "payload" value
        List<NameValuePair> nvps = new ArrayList<NameValuePair>(1);
        nvps.add(new BasicNameValuePair("payload", json));
        post.setEntity(new UrlEncodedFormEntity(nvps, "UTF-8"));
    } else {
        // post as JSON
        StringEntity entity = new StringEntity(json, "UTF-8");
        entity.setContentType("application/json");
        post.setEntity(entity);
    }

    HttpResponse response = client.execute(post);
    int rc = response.getStatusLine().getStatusCode();

    if (HttpStatus.SC_OK == rc) {
        // This is the expected result code
        // replace this with post.closeConnection() after JGit updates to HttpClient 4.2
        post.abort();
    } else {
        String result = null;
        InputStream is = response.getEntity().getContent();
        try {
            byte[] buffer = new byte[8192];
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            int len = 0;
            while ((len = is.read(buffer)) > -1) {
                os.write(buffer, 0, len);
            }
            result = os.toString("UTF-8");
        } finally {
            if (is != null) {
                is.close();
            }
        }

        log.error("FlowDock plugin sent:");
        log.error(json);
        log.error("FlowDock returned:");
        log.error(result);

        throw new IOException(String.format("FlowDock Error (%s): %s", rc, result));
    }
}

From source file:com.andrestrequest.http.DefaultRequestHandler.java

private StringEntity getEntity(Object body) {

    AcceptedMediaType mediaType = AndRestConfig.getResponseMediaType();

    String json = null;//ParserUtil.toJson(body);

    if (body instanceof JSONObject || body instanceof String) {
        // ? JSON 
        json = body.toString();/* www  .j  a v  a 2  s  .  com*/
    } else if (body != null) {
        json = GsonUtil.toJson(body);
    } else {
        return null;
    }

    StringEntity entity = null;
    try {
        entity = new StringEntity(json, AndRestConfig.getCharset());
        entity.setContentType(mediaType.getMediaType());
    } catch (UnsupportedEncodingException e) {
        throw new RequestInvalidException("Unable to encode json string for making request.", e);
    }

    return entity;
}

From source file:org.urbanstew.soundcloudapi.test.RequestTest.java

public final void testPostDeleteCommentXML() throws Exception {
    assertTrue(sTrackId >= 0);//from  w w  w.  jav a  2s.c o m

    String commentUrl = "tracks/" + sTrackId + "/comments";

    StringEntity entity = new StringEntity("<comment><body>This is a test XML comment</body></comment>");
    entity.setContentType("application/xml");

    HttpResponse response = mApi.post(commentUrl, entity);
    assertEquals(201, response.getStatusLine().getStatusCode());

    response = mApi.delete("comments/" + getId(response));
    assertEquals(200, response.getStatusLine().getStatusCode());
}

From source file:com.t2.drupalsdk.ServicesClient.java

public void post(String url, JSONObject params, AsyncHttpResponseHandler responseHandler) {
    StringEntity se = null;
    try {/*www. java 2s .c o  m*/
        se = new StringEntity(params.toString());
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    Log.d(TAG, "url = " + getAbsoluteUrl(url));
    //        Log.d(TAG, "mAsyncHttpClient = " + mAsyncHttpClient);

    //        // TODO: change to debug - it's at error now simply for readability
    //        HttpContext context = mAsyncHttpClient.getHttpContext();
    //        CookieStore store1 = (CookieStore) context.getAttribute(ClientContext.COOKIE_STORE);
    //        Log.e(TAG, "Cookies for AsyncClient = " + store1.getCookies().toString());       

    mAsyncHttpClient.post(null, getAbsoluteUrl(url), se, "application/json", responseHandler);
}

From source file:com.simple.toadiot.rtinfosdk.http.DefaultRequestHandler.java

private StringEntity getEntity(Object body) {

    AcceptedMediaType mediaType = AppConfig.getResponseMediaType();

    String json = null;//ParserUtil.toJson(body);

    if (body instanceof JSONObject || body instanceof String) {
        // ? JSON 
        json = body.toString();//w w  w.  j a  v  a  2  s  .  c  o m
    } else if (body != null) {
        json = ParserUtil.toJson(body);
    } else {
        return null;
    }

    StringEntity entity = null;
    try {
        entity = new StringEntity(json, AppConfig.getCharset());
        entity.setContentType(mediaType.getMediaType());
    } catch (UnsupportedEncodingException e) {
        throw new RequestInvalidException("Unable to encode json string for making request.", e);
    }

    return entity;
}

From source file:com.gitblit.plugin.hipchat.HipChatter.java

/**
 * Send a payload message./*  w  w w  .  j  a  va 2  s .  c o  m*/
 *
 * @param payload
 * @throws IOException
 */
public void send(Payload payload) throws IOException {

    RepoConfig config = payload.getConfig();

    if (payload.getConfig() == null) {
        setRoom(null, payload);
    }

    String hipchatUrl = String.format("https://api.hipchat.com/v2/room/%s/notification?auth_token=%s",
            config.getRoomName(), config.getToken());

    Gson gson = new GsonBuilder().create();

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(hipchatUrl);
    post.getParams().setParameter(CoreProtocolPNames.USER_AGENT, Constants.NAME + "/" + Constants.getVersion());
    post.getParams().setParameter(CoreProtocolPNames.HTTP_CONTENT_CHARSET, "UTF-8");

    client.getParams().setParameter(AllClientPNames.CONNECTION_TIMEOUT, 5000);
    client.getParams().setParameter(AllClientPNames.SO_TIMEOUT, 5000);

    String body = gson.toJson(payload);
    StringEntity entity = new StringEntity(body, "UTF-8");
    entity.setContentType("application/json");
    post.setEntity(entity);

    HttpResponse response = client.execute(post);
    int rc = response.getStatusLine().getStatusCode();

    if (HttpStatus.SC_NO_CONTENT == rc) {
        // This is the expected result code
        // https://www.hipchat.com/docs/apiv2/method/send_room_notification
        // replace this with post.closeConnection() after JGit updates to HttpClient 4.2
        post.abort();
    } else {
        String result = null;
        InputStream is = response.getEntity().getContent();
        try {
            byte[] buffer = new byte[8192];
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            int len = 0;
            while ((len = is.read(buffer)) > -1) {
                os.write(buffer, 0, len);
            }
            result = os.toString("UTF-8");
        } finally {
            if (is != null) {
                is.close();
            }
        }

        log.error("HipChat plugin sent:");
        log.error(body);
        log.error("HipChat returned:");
        log.error(result);

        throw new IOException(String.format("HipChat Error (%s): %s", rc, result));
    }
}