Example usage for org.apache.http.protocol HTTP CONTENT_TYPE

List of usage examples for org.apache.http.protocol HTTP CONTENT_TYPE

Introduction

In this page you can find the example usage for org.apache.http.protocol HTTP CONTENT_TYPE.

Prototype

String CONTENT_TYPE

To view the source code for org.apache.http.protocol HTTP CONTENT_TYPE.

Click Source Link

Usage

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 w w . j a  va 2  s . co 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:org.apache.synapse.mediators.builtin.PropertyMediatorTest.java

public void testSpecialPropertiesHandling() throws Exception {

    MessageContext synCtx = TestUtils.createLightweightSynapseMessageContext("<empty/>");

    PropertyMediator propMediatorEight = new PropertyMediator();
    propMediatorEight.setName(HTTP.CONTENT_TYPE);
    propMediatorEight.setValue("application/xml");
    propMediatorEight.setScope(XMLConfigConstants.SCOPE_TRANSPORT);

    PropertyMediator propMediatorNine = new PropertyMediator();
    propMediatorNine.setName(org.apache.axis2.Constants.Configuration.MESSAGE_TYPE);
    propMediatorNine.setValue("application/json");
    propMediatorNine.setScope(XMLConfigConstants.SCOPE_AXIS2);

    propMediatorEight.mediate(synCtx);//from www.  j ava2  s  .  co m
    propMediatorNine.mediate(synCtx);

    org.apache.axis2.context.MessageContext axisCtx = ((Axis2MessageContext) synCtx).getAxis2MessageContext();
    Map transportHeaders = (Map) axisCtx.getProperty(org.apache.axis2.context.MessageContext.TRANSPORT_HEADERS);
    assertNotNull(transportHeaders);
    assertTrue("application/json".equals(transportHeaders.get(HTTP.CONTENT_TYPE)));
}

From source file:com.navercorp.volleyextensions.request.JacksonRequestTest.java

@Test
public void networkResponseShouldNotBeParsedWithUnsupportedException() throws JsonProcessingException {
    // Given/*from   w w  w.ja va2s.  c  om*/
    String content = "{\"imageUrl\":\"http://static.naver.com\"}";
    HashMap<String, String> headers = new HashMap<String, String>();
    headers.put(HTTP.CONTENT_TYPE, "text/html;charset=UTF-14");
    NetworkResponse networkResponse = new NetworkResponse(content.getBytes(), headers);
    JacksonRequest<News> request = new JacksonRequest<News>(url, News.class, listener);
    // When
    Response<News> response = request.parseNetworkResponse(networkResponse);
    // Then
    assertNull(response.result);
    assertThat(response.error, is(instanceOf(ParseError.class)));
    assertThat(response.error.getCause(), is(instanceOf(UnsupportedEncodingException.class)));
}

From source file:com.navercorp.volleyextensions.request.Jackson2RequestTest.java

@Test
public void networkResponseShouldNotBeParsedWithUnsupportedException() throws JsonProcessingException {
    // Given//from  ww  w .  j a va  2s.c om
    String content = "{\"imageUrl\":\"http://static.naver.com\"}";
    HashMap<String, String> headers = new HashMap<String, String>();
    headers.put(HTTP.CONTENT_TYPE, "text/html;charset=UTF-14");
    NetworkResponse networkResponse = new NetworkResponse(content.getBytes(), headers);
    Jackson2Request<News> request = new Jackson2Request<News>(url, News.class, listener);
    // When
    Response<News> response = request.parseNetworkResponse(networkResponse);
    // Then
    assertNull(response.result);
    assertThat(response.error, is(instanceOf(ParseError.class)));
    assertThat(response.error.getCause(), is(instanceOf(UnsupportedEncodingException.class)));
}

From source file:com.scvngr.levelup.core.net.LevelUpRequestTest.java

@SmallTest
public void testHeaders_withAccessToken() {
    final MockAccessTokenRetriever retreiver = new MockAccessTokenRetriever();
    final LevelUpRequest request = new LevelUpRequest(mMockContext, HttpMethod.POST, TEST_API_VERSION,
            TEST_ENDPOINT, null, null, retreiver);

    final HashMap<String, String> expectedHeaders = new HashMap<String, String>(
            RequestUtils.getDefaultRequestHeaders(mMockContext));
    expectedHeaders.put(HTTP.CONTENT_TYPE, RequestUtils.HEADER_CONTENT_TYPE_JSON);
    expectedHeaders.put(LevelUpRequest.HEADER_LEVELUP_API_KEY, "test_api_key");
    expectedHeaders.put(LevelUpRequest.HEADER_AUTHORIZATION,
            String.format(Locale.US, LevelUpRequest.AUTH_TOKEN_TYPE_FORMAT,
                    NullUtils.nonNullContract(retreiver.getAccessToken(mMockContext)).getAccessToken()));

    final Map<String, String> actualHeaders = request.getRequestHeaders(mMockContext);
    assertEquals(expectedHeaders, actualHeaders);
}

From source file:org.neo4j.ogm.drivers.http.request.HttpRequest.java

public static CloseableHttpResponse execute(CloseableHttpClient httpClient, HttpRequestBase request,
        Credentials credentials) throws HttpRequestException {

    LOGGER.debug("Thread: {}, request: {}", Thread.currentThread().getId(), request);

    CloseableHttpResponse response;/*from w ww .ja va 2s. c o m*/

    request.setHeader(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
    request.setHeader(new BasicHeader(HTTP.USER_AGENT, "neo4j-ogm.java/2.0"));
    request.setHeader(new BasicHeader("Accept", "application/json;charset=UTF-8"));

    HttpAuthorization.authorize(request, credentials);

    // use defaults: 3 retries, 2 second wait between attempts
    RetryOnExceptionStrategy retryStrategy = new RetryOnExceptionStrategy();

    while (retryStrategy.shouldRetry()) {

        try {

            response = httpClient.execute(request);

            StatusLine statusLine = response.getStatusLine();
            HttpEntity responseEntity = response.getEntity();

            if (statusLine.getStatusCode() >= 300) {
                String responseText = statusLine.getReasonPhrase();
                if (responseEntity != null) {
                    responseText = parseError(EntityUtils.toString(responseEntity));
                    LOGGER.warn("Thread: {}, response: {}", Thread.currentThread().getId(), responseText);
                }
                throw new HttpResponseException(statusLine.getStatusCode(), responseText);
            }
            if (responseEntity == null) {
                throw new ClientProtocolException("Response contains no content");
            }

            return response; // don't close response yet, it is not consumed!
        }

        // if we didn't get a response at all, try again
        catch (NoHttpResponseException nhre) {
            LOGGER.warn("Thread: {}, No response from server:  Retrying in {} milliseconds, retries left: {}",
                    Thread.currentThread().getId(), retryStrategy.getTimeToWait(),
                    retryStrategy.numberOfTriesLeft);
            retryStrategy.errorOccurred();
        } catch (RetryException re) {
            throw new HttpRequestException(request, re);
        } catch (ClientProtocolException uhe) {
            throw new ConnectionException(request.getURI().toString(), uhe);
        } catch (IOException ioe) {
            throw new HttpRequestException(request, ioe);
        }

        // here we catch any exception we throw above (plus any we didn't throw ourselves),
        // log the problem, close any connection held by the request
        // and then rethrow the exception to the caller.
        catch (Exception exception) {
            LOGGER.warn("Thread: {}, exception: {}", Thread.currentThread().getId(),
                    exception.getCause().getLocalizedMessage());
            request.releaseConnection();
            throw exception;
        }
    }
    throw new RuntimeException("Fatal Exception: Should not have occurred!");
}

From source file:org.wso2.carbon.core.transports.util.CertProcessor.java

/**
 * Pump out the certificate/*from  w w  w . jav  a 2  s .  c o  m*/
 *
 * @param certificate  cert
 * @param response     response
 * @param outputStream out stream
 * @param serviceName  service name
 * @throws AxisFault will be thrown
 */
private void serializeCert(Certificate certificate, CarbonHttpResponse response, OutputStream outputStream,
        String serviceName) throws AxisFault {
    try {
        response.addHeader(HTTP.CONTENT_TYPE, "application/octet-stream");
        response.addHeader("Content-Disposition", "filename=" + serviceName + ".cert");
        outputStream.write(certificate.getEncoded());
    } catch (CertificateEncodingException e) {
        String msg = "Could not get encoded format of certificate";
        log.error(msg, e);
        throw new AxisFault(msg, e);
    } catch (IOException e) {
        String msg = "Faliour when serializing to stream";
        log.error(msg, e);
        throw new AxisFault(msg, e);
    } finally {
        try {
            outputStream.flush();
        } catch (IOException e) {
            String msg = "Faliour when serializing to stream";
            log.error(msg, e);
        }
    }
}

From source file:org.alfresco.test.util.AlfrescoHttpClient.java

/**
 * Populate HTTP message call with given content.
 * /* w  w w. j av a 2 s .  c o m*/
 * @param json {@link JSONObject} content
 * @return {@link StringEntity} content.
 * @throws UnsupportedEncodingException if unsupported
 */
public StringEntity setMessageBody(final JSONObject json) throws UnsupportedEncodingException {
    if (json == null || json.toString().isEmpty()) {
        throw new IllegalArgumentException("JSON Content is required.");
    }
    StringEntity se = new StringEntity(json.toString(), UTF_8_ENCODING);
    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, MIME_TYPE_JSON));
    if (logger.isDebugEnabled()) {
        logger.debug("Json string value: " + se);
    }
    return se;
}

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

public void put(String url, JSONObject params, AsyncHttpResponseHandler responseHandler) {
    StringEntity se = null;/*from w  ww  .j a  v a 2 s  .  co  m*/
    try {
        se = new StringEntity(params.toString());
    } catch (UnsupportedEncodingException e) {
        Log.e(TAG, e.toString());
        e.printStackTrace();
    }
    se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    Log.d(TAG, "url = " + getAbsoluteUrl(url));

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

From source file:AdminAssetCreateTest.java

@Test
public void testServerCreateFileAsset() {
    running(getTestServer(), HTMLUNIT, new Callback<TestBrowser>() {
        public void invoke(TestBrowser browser) {
            serverCreateFileAsset();//w  ww  .java2  s .c om

            continueOnFail(true);

            setHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
            setHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC);
            setHeader(HTTP.CONTENT_TYPE, MediaType.APPLICATION_JSON);
            httpRequest(getURLAddress(), getMethod(), mParametersFile);
            assertServer("testServerCreateFileAsset. wrong media type", Status.BAD_REQUEST, null, false);

            continueOnFail(false);

            serverDeleteFileAsset();
        }
    });
}