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:AdminAssetGetTest.java

@Test
public void testRouteGet() {
    running(getFakeApplication(), new Runnable() {
        public void run() {
            FakeRequest request = new FakeRequest(getMethod(), getRouteAddress());
            request = request.withHeader(TestConfig.KEY_APPCODE, TestConfig.VALUE_APPCODE);
            request = request.withHeader(TestConfig.KEY_AUTH, TestConfig.AUTH_ADMIN_ENC);
            request = request.withHeader(HTTP.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED);
            Result result = routeAndCall(request);
            assertRoute(result, "testRouteGet", Status.OK, null, false);
        }/*from   w ww  .  jav a 2  s.  com*/
    });
}

From source file:ste.web.http.HttpUtils.java

/**
 * Returns true if the request content is supposed to contain a json object
 * as per the specified content type/*w  w w . j  av a  2 s  .  co  m*/
 * 
 * @param request the request
 * 
 * @return true if the content type is "application/json", false otherwise
 */
public static boolean hasJSONBody(HttpRequest request) {
    Header[] headers = request.getHeaders(HTTP.CONTENT_TYPE);
    if (headers.length == 0) {
        return false;
    }

    String contentType = headers[0].getValue();
    return CONTENT_TYPE_JSON.equals(contentType) || contentType.startsWith(CONTENT_TYPE_JSON + ";");
}

From source file:org.wso2.carbon.tryit.TryitRequestProcessor.java

public void process(CarbonHttpRequest request, CarbonHttpResponse response,
        ConfigurationContext configurationContext) throws Exception {
    OutputStream outputStream = response.getOutputStream();
    String requestURL = request.getRequestURL() + "?" + request.getQueryString();
    String serviceParameter = request.getParameter(WSDL2FormGenerator.SERVICE_QUERY_PARAM);
    String endpointParameter = request.getParameter(WSDL2FormGenerator.ENDPOINT_QUERY_PARAM);
    String operationParameter = request.getParameter(WSDL2FormGenerator.OPERATION_PARAM);

    response.addHeader(HTTP.CONTENT_TYPE, "text/html; charset=utf-8");

    try {//from  w w w .  j  a va  2s  .com
        Result result = new StreamResult(outputStream);
        String str = WSDL2FormGenerator.getInstance().getInternalTryit(result, configurationContext, requestURL,
                serviceParameter, operationParameter, endpointParameter, true);
        if (!str.equals(WSDL2FormGenerator.SUCCESS)) {
            response.setRedirect(str);
        }
    } catch (CarbonException e) {
        log.error(e);
        if (e.getMessage().equals(WSDL2FormGenerator.SERVICE_INACTIVE)) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            outputStream.write(("<h4>Requested Service is inactive. Cannot generate stubs.</h4>").getBytes());
            outputStream.flush();
        } else if (e.getMessage().equals(WSDL2FormGenerator.SERVICE_NOT_FOUND)) {
            response.setStatus(HttpServletResponse.SC_SERVICE_UNAVAILABLE);
            outputStream.write(("<h4>Service cannot be found. Cannot display <em>Stub</em>.</h4>").getBytes());
            outputStream.flush();
        } else {
            response.setError(HttpServletResponse.SC_NOT_FOUND);
            outputStream.write(("<h4>" + e.getMessage() + "</h4>").getBytes());
            outputStream.flush();
        }
    }
}

From source file:com.vimc.ahttp.NetworkResponse.java

public String getCharset() {
    String contentType = headers.get(HTTP.CONTENT_TYPE);
    if (contentType != null) {
        String[] params = contentType.split(";");
        for (int i = 1; i < params.length; i++) {
            String[] pair = params[i].trim().split("=");
            if (pair.length == 2) {
                if (pair[0].equals("charset")) {
                    return pair[1];
                }//from  w  w w .  ja v a  2  s . c o  m
            }
        }
    }

    return HTTP.DEFAULT_CONTENT_CHARSET;
}

From source file:ai.eve.volley.request.JsonRequest.java

@Override
public void getBody(HttpURLConnection connection) {
    try {//  w  w  w  . ja  v a  2 s  .  c o m
        if (mRequestBody != null) {
            connection.setDoOutput(true);
            connection.addRequestProperty(HTTP.CONTENT_TYPE, getBodyContentType());
            DataOutputStream out = new DataOutputStream(connection.getOutputStream());
            out.write(mRequestBody.getBytes(PROTOCOL_CHARSET));
            out.close();
        }
    } catch (UnsupportedEncodingException uee) {
        NetroidLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody,
                PROTOCOL_CHARSET);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:com.intellij.tasks.impl.httpclient.ResponseUtil.java

public static String getResponseContentAsString(@Nonnull HttpMethod response) throws IOException {
    // Sometimes servers don't specify encoding and HttpMethod#getResponseBodyAsString
    // by default decodes from Latin-1, so we got to read byte stream and decode it from UTF-8
    // manually//from  w w  w . jav  a 2 s  .  c  o  m
    //if (!response.hasBeenUsed()) {
    //  return "";
    //}
    org.apache.commons.httpclient.Header header = response.getResponseHeader(HTTP.CONTENT_TYPE);
    if (header != null && header.getValue().contains("charset")) {
        // ISO-8859-1 if charset wasn't specified in response
        return StringUtil.notNullize(response.getResponseBodyAsString());
    } else {
        InputStream stream = response.getResponseBodyAsStream();
        return stream == null ? "" : StreamUtil.readText(stream, DEFAULT_CHARSET);
    }
}

From source file:HttpClient.HttpCalendarClient.java

private String send_request(JSONObject req, String operation) {
    String success = null;//  w  w  w .  j  a  v  a  2 s .c o  m
    //imposto il "contenitore" della risposta JSON
    CloseableHttpResponse response1 = null;
    //creo una richiesta di tipo POSTal WS
    HttpPost r_post = new HttpPost(url + operation);
    //imposto l'HEADER della richiesta a JSON
    r_post.addHeader(new BasicHeader("Content-Type", "application/json"));
    //Creo l'entita' da inserire nella richiesta, ipostandone come contenuto il JSON
    StringEntity param = new StringEntity(req.toJSONString(), "UTF8");
    param.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    r_post.setEntity(param);
    //EFFETTUO LA RICHIESTA
    try {
        //EFFETTUO la richiesta ed attendo la risposta dal WS
        response1 = httpclient.execute(r_post);
        if (response1.getEntity() != null) {
            //converto lo stream ottenuto in un oggetto JSON
            JSONObject risposta = convertStreamToJson(response1.getEntity().getContent());
            if (risposta != null) {
                String result = (String) risposta.get("code");
                if (result.equalsIgnoreCase("201")) {
                    success = (String) risposta.get("id");
                }
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(HttpCalendarClient.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            response1.close();
        } catch (IOException ex) {
            Logger.getLogger(HttpCalendarClient.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    return success;
}

From source file:com.photon.phresco.Screens.HttpRequest.java

/**
 * Send the JSON data to specified URL and get the httpResponse back
 *
 * @param sURL/*  w w w.jav a 2 s .  co m*/
 * @param jObject
 * @return InputStream
 * @throws IOException
 */
public static InputStream post(String sURL, JSONObject jObject) throws IOException {
    HttpResponse httpResponse = null;
    InputStream is = null;

    HttpPost httpPostRequest = new HttpPost(sURL);
    HttpEntity entity;

    httpPostRequest.setHeader("Accept", "application/json");
    httpPostRequest.setHeader(HTTP.CONTENT_TYPE, "application/json");
    httpPostRequest.setEntity(new ByteArrayEntity(jObject.toString().getBytes("UTF-8")));
    HttpParams httpParameters = new BasicHttpParams();
    // Set the timeout in milliseconds until a connection is established.
    int timeoutConnection = TIME_OUT;
    HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
    // Set the default socket timeout (SO_TIMEOUT)
    // in milliseconds which is the timeout for waiting for data.
    int timeoutSocket = TIME_OUT;
    HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);

    DefaultHttpClient httpClient = new DefaultHttpClient(httpParameters);
    httpResponse = httpClient.execute(httpPostRequest);

    if (httpResponse != null) {
        entity = httpResponse.getEntity();
        is = entity.getContent();
    }
    return is;
}

From source file:siarhei.luskanau.gps.tracker.free.service.sync.tracking.json.SendJsonForm.java

public static void sendLocationsForm(Context context) throws Exception {
    ServerEntity serverEntity = AppSettings.getServerEntity(context);

    for (;;) {//from w  w  w .  j a  v  a  2  s. co  m
        List<LocationModel> locationEntities = LocationDAO.queryNextLocations(context, 100);
        if (locationEntities != null && locationEntities.size() > 0) {

            String requestJsonString = AppConstants.GSON.toJson(locationEntities);

            HttpPost httpPost = new HttpPost(serverEntity.server_address);
            httpPost.addHeader(HTTP.CONTENT_TYPE, "application/x-www-form-urlencoded;charset=UTF-8");
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
            nameValuePairs.add(new BasicNameValuePair("track", requestJsonString));
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            if (DEBUG) {
                Log.d(TAG, "Send request: " + httpPost.getURI() + " " + requestJsonString);
            }
            String responseJsonString = read(requestInputStream(httpPost));
            if (DEBUG) {
                Log.d(TAG, "Received response: " + responseJsonString);
            }

            SendLocationsResponseDTO statusResponse = AppConstants.GSON.fromJson(responseJsonString,
                    SendLocationsResponseDTO.class);
            if (statusResponse != null && statusResponse.success) {
                LocationDAO.deleteLocations(context, locationEntities);
                incPacketCounter(context, locationEntities.size());
                Log.d(context.getPackageName(),
                        "Packet is send: " + locationEntities.size() + " " + responseJsonString);
            } else {
                Log.e(context.getPackageName(), "Packet is not send: " + responseJsonString);
                break;
            }
        } else {
            break;
        }
    }
}