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:ch.cyberduck.core.http.DelayedHttpMultipartEntity.java

/**
 * @param status Length//  w  w w. j  a  v a2 s  .  c o m
 */
public DelayedHttpMultipartEntity(final String filename, final TransferStatus status, final String boundary) {
    this.status = status;
    final StringBuilder multipartHeader = new StringBuilder();
    multipartHeader.append(TWO_DASHES);
    multipartHeader.append(boundary);
    multipartHeader.append(CR_LF);
    multipartHeader
            .append(String.format("Content-Disposition: form-data; name=\"file\"; filename=\"%s\"", filename));
    multipartHeader.append(CR_LF);
    multipartHeader.append(String.format("%s: %s", HTTP.CONTENT_TYPE,
            StringUtils.isBlank(status.getMime()) ? MimeTypeService.DEFAULT_CONTENT_TYPE : status.getMime()));
    multipartHeader.append(CR_LF);
    multipartHeader.append(CR_LF);
    header = encode(MIME.DEFAULT_CHARSET, multipartHeader.toString()).buffer();
    final StringBuilder multipartFooter = new StringBuilder();
    multipartFooter.append(CR_LF);
    multipartFooter.append(TWO_DASHES);
    multipartFooter.append(boundary);
    multipartFooter.append(TWO_DASHES);
    multipartFooter.append(CR_LF);
    footer = encode(MIME.DEFAULT_CHARSET, multipartFooter.toString()).buffer();
}

From source file:org.bishoph.oxdemo.util.DeleteTask.java

@Override
protected JSONObject doInBackground(Object... params) {
    try {/*from  w  w w.j  ava2  s.c om*/
        String uri = (String) params[0];
        int object_id = (Integer) params[1];
        Log.v("OXDemo", "Attempting to delete task " + object_id + " in folder " + folder_id + " on " + uri);

        // [{"id":25,"folder":27}]
        JSONObject jsonobject = new JSONObject();
        jsonobject.put("id", object_id);
        jsonobject.put("folder", folder_id);
        JSONArray jsonarray = new JSONArray();
        jsonarray.put(jsonobject);

        HttpPut httput = new HttpPut(uri);
        StringEntity stringentity = new StringEntity(jsonarray.toString());
        Log.v("OXDemo", "JSON ? " + stringentity);
        stringentity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json; charset=UTF-8")); // 
        httput.setHeader("Accept", "application/json, text/javascript");
        httput.setHeader("Content-type", "application/json");
        httput.setEntity(stringentity);

        HttpResponse response = httpclient.execute(httput, localcontext);
        Log.v("OXDemo", "Delete task " + object_id);
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity);
        Log.d("OXDemo", "<<<<<<<\n" + result + "\n\n");
        JSONObject jsonObj = new JSONObject(result);
        return jsonObj;
    } catch (JSONException e) {
        Log.e("OXDemo", e.getMessage());
    } catch (ClientProtocolException e) {
        Log.e("OXDemo", e.getMessage());
    } catch (IOException e) {
        Log.e("OXDemo", e.getMessage());
    }
    return null;
}

From source file:org.wso2.carbon.wsdl2form.StubRequestProcessor.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 languageParameter = request.getParameter(WSDL2FormGenerator.LANGUAGE_QUERY_PARAM);
    String localhostParameter = request.getParameter(WSDL2FormGenerator.LOCALHOST_QUERY_PARAM);
    String contentTypeParameter = request.getParameter(WSDL2FormGenerator.CONTENT_TYPE_QUERY_PARAM);

    try {//from ww  w.  j  a v a  2s  .co  m
        Result result = new StreamResult(outputStream);
        String contentType = WSDL2FormGenerator.getInstance().getJSStub(result, configurationContext,
                requestURL, serviceParameter, endpointParameter, languageParameter, localhostParameter,
                contentTypeParameter);
        response.addHeader(HTTP.CONTENT_TYPE, contentType);
    } catch (CarbonException e) {
        log.error("Cannot generate stub", e);
        response.addHeader(HTTP.CONTENT_TYPE, "text/html; charset=utf-8");
        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();
            return;
        } 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();
            return;
        } else if (e.getMessage().equals(WSDL2FormGenerator.UNSUPPORTED_LANG)) {
            response.setError(HttpServletResponse.SC_NOT_FOUND);
            outputStream.write(("<h4>Unsupported lang parameter " + languageParameter + "</h4>").getBytes());
            outputStream.flush();
            return;
        } else {
            response.setError(HttpServletResponse.SC_NOT_FOUND);
            response.addHeader(HTTP.CONTENT_TYPE, "text/html; charset=utf-8");
            outputStream.write(("<h4>" + e.getMessage() + "</h4>").getBytes());
            outputStream.flush();
            return;
        }
    }
}

From source file:groovesquid.Grooveshark.java

public static String sendRequest(String method, HashMap<String, Object> parameters) {
    if (tokenExpires <= new Date().getTime() && tokenExpires != 0 && !"initiateSession".equals(method)
            && !"getCommunicationToken".equals(method) && !"getCountry".equals(method)) {
        try {//from  w  ww. j  av  a  2 s  . c o m
            InitThread initThread = new InitThread();
            initThread.start();
            initThread.getLatch().await();
        } catch (InterruptedException ex) {
            log.log(Level.SEVERE, null, ex);
        }
    }
    String responseContent = null;
    HttpEntity httpEntity = null;
    try {
        Client client = clients.getHtmlshark();

        String protocol = "http://";

        if (method.equals("getCommunicationToken")) {
            protocol = "https://";
        }

        String url = protocol + "grooveshark.com/more.php?" + method;

        for (String jsqueueMethod : jsqueueMethods) {
            if (jsqueueMethod.equals(method)) {
                client = clients.getJsqueue();
                break;
            }
        }

        header.put("client", client.getName());
        header.put("clientRevision", client.getRevision());
        header.put("privacy", "0");
        header.put("uuid", uuid);
        header.put("country", country);
        if (!method.equals("initiateSession")) {
            header.put("session", session);
            header.put("token", generateToken(method, client.getSecret()));
        }

        Gson gson = new Gson();
        String jsonString = gson.toJson(new JsonRequest(header, parameters, method));
        log.info(">>> " + jsonString);

        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader(HTTP.CONTENT_TYPE, "application/json");
        httpPost.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE);
        httpPost.setHeader(HTTP.USER_AGENT,
                "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31");
        httpPost.setHeader("Referer", "http://grooveshark.com/JSQueue.swf?" + client.getRevision());
        httpPost.setHeader("Content-Language", "en-US");
        httpPost.setHeader("Cache-Control", "max-age=0");
        httpPost.setHeader("Accept", "*/*");
        httpPost.setHeader("Accept-Charset", "utf-8,ISO-8859-1;q=0.7,*;q=0.3");
        httpPost.setHeader("Accept-Language", "de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4");
        httpPost.setHeader("Accept-Encoding", "gzip,deflate,sdch");
        httpPost.setHeader("Origin", "http://grooveshark.com");
        if (!method.equals("initiateSession")) {
            httpPost.setHeader("Cookie", "PHPSESSID=" + session);
        }
        httpPost.setEntity(new StringEntity(jsonString, "UTF-8"));

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        if (Main.getConfig().getProxyHost() != null && Main.getConfig().getProxyPort() != null) {
            httpClientBuilder
                    .setProxy(new HttpHost(Main.getConfig().getProxyHost(), Main.getConfig().getProxyPort()));
        }
        HttpClient httpClient = httpClientBuilder.build();
        HttpResponse httpResponse = httpClient.execute(httpPost);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        httpEntity = httpResponse.getEntity();

        StatusLine statusLine = httpResponse.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            httpEntity.writeTo(baos);
        } else {
            throw new RuntimeException("method " + method + ": " + statusLine);
        }

        responseContent = baos.toString("UTF-8");

    } catch (Exception ex) {
        Logger.getLogger(Grooveshark.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
        try {
            EntityUtils.consume(httpEntity);
        } catch (IOException ex) {
            Logger.getLogger(Grooveshark.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    log.info("<<< " + responseContent);
    return responseContent;
}

From source file:fr.xebia.workshop.android.core.utils.ServerUtils.java

private static HttpRequestBase buildUserRegistationRequest(PlusClient plusClient)
        throws JSONException, UnsupportedEncodingException {
    HttpPost postRequest = new HttpPost(USER_REGISTRATION_URL);
    postRequest.setHeader(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    JSONObject regObject = new JSONObject();
    regObject.put("email", plusClient.getAccountName());
    Person currentPerson = plusClient.getCurrentPerson();
    regObject.put("firstName", currentPerson.getName().getGivenName());
    regObject.put("lastName", currentPerson.getName().getFamilyName());
    postRequest.setEntity(new StringEntity(regObject.toString()));
    return postRequest;
}

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

public void process(CarbonHttpRequest request, CarbonHttpResponse response, ConfigurationContext configCtx)
        throws Exception {
    String requestURI = request.getRequestURI();
    String contextPath = configCtx.getServiceContextPath();
    String serviceName = requestURI.substring(requestURI.indexOf(contextPath) + contextPath.length() + 1);
    AxisService axisService = configCtx.getAxisConfiguration().getServiceForActivation(serviceName);
    OutputStream outputStream = response.getOutputStream();
    if (axisService != null) {
        if (GhostDeployerUtils.isGhostService(axisService)) {
            // if the existing service is a ghost service, deploy the actual one
            axisService = GhostDeployerUtils.deployActualService(configCtx.getAxisConfiguration(), axisService);
        }/* ww  w.j a va 2s.  c om*/
        if (!axisService.isActive()) {
            response.addHeader(HTTP.CONTENT_TYPE, "text/html");
            outputStream.write(
                    ("<h4>Service " + serviceName + " is inactive. Cannot display policies.</h4>").getBytes());
            outputStream.flush();
        } else {
            PolicyInclude policyInclude = axisService.getPolicyInclude();
            if (policyInclude == null) {
                response.addHeader(HTTP.CONTENT_TYPE, "text/html");
                outputStream.write("<h4>Policy element is not found!</h4>".getBytes());
                outputStream.flush();
                return;

            }
            ArrayList policyElements = policyInclude.getPolicyElements();

            if (policyElements == null) {
                response.addHeader(HTTP.CONTENT_TYPE, "text/html");
                outputStream.write("<h4>Policy elements not found!</h4>".getBytes());
                outputStream.flush();
                return;
            }

            PolicyRegistry reg = policyInclude.getPolicyRegistry();

            ExternalPolicySerializer serializer = new ExternalPolicySerializer();
            if (configCtx.getAxisConfiguration().getLocalPolicyAssertions() != null) {
                serializer.setAssertionsToFilter(configCtx.getAxisConfiguration().getLocalPolicyAssertions());
            }

            if (policyElements.size() == 1) {
                response.addHeader(HTTP.CONTENT_TYPE, "text/xml");
                if (policyElements.get(0) instanceof Policy) {
                    Policy policy = (Policy) policyElements.get(0);
                    serializer.serialize(policy, outputStream);
                } else if (policyElements.get(0) instanceof PolicyReference) {
                    String key = ((PolicyReference) policyElements.get(0)).getURI();
                    if (key.startsWith("#")) {
                        key = key.substring(key.indexOf('#') + 1);
                    }

                    Policy p = reg.lookup(key);
                    if (p == null) {
                        response.addHeader(HTTP.CONTENT_TYPE, "text/html");
                        outputStream.write("<h4>Policy element not found!</h4>".getBytes());
                    } else {
                        serializer.serialize(p, outputStream);
                    }
                }
            } else {
                // for many policies
                String idParam = request.getParameter("id");
                if (idParam != null) {
                    Object policyObject = policyElements.get(Integer.parseInt(idParam));
                    if (policyObject != null) {
                        response.addHeader(HTTP.CONTENT_TYPE, "text/xml");
                        if (policyObject instanceof Policy) {
                            Policy policy = (Policy) policyObject;
                            serializer.serialize(policy, outputStream);
                        } else if (policyObject instanceof PolicyReference) {
                            String key = ((PolicyReference) policyObject).getURI();
                            if (key.startsWith("#")) {
                                key = key.substring(key.indexOf('#') + 1);
                            }
                            Policy p = reg.lookup(key);
                            if (p == null) {
                                response.addHeader(HTTP.CONTENT_TYPE, "text/html");
                                outputStream.write("<h4>Policy element not found!</h4>".getBytes());
                            } else {
                                serializer.serialize(p, outputStream);
                            }
                        }
                    } else {
                        response.addHeader(HTTP.CONTENT_TYPE, "text/html");
                        outputStream.write("<h4>Policy not found!</h4>".getBytes());
                    }
                } else {
                    if (policyElements.size() == 0) {
                        response.addHeader(HTTP.CONTENT_TYPE, "text/html");
                        outputStream.write("<h4>Policy not found!</h4>".getBytes());
                    } else {
                        String ipAddress = "http://" + NetworkUtils.getLocalHostname() + ":"
                                + CarbonUtils.getTransportPort(configCtx, "http");
                        ServerConfigurationService serverCofig = CarbonCoreDataHolder.getInstance()
                                .getServerConfigurationService();
                        outputStream.write(("<html><head>" + "<title>WSO2 Server v"
                                + serverCofig.getFirstProperty("Version") + " Management Console - "
                                + axisService.getName() + " Service Policies</title>" + "</head>" + "<body>"
                                + "<b>Policies for " + axisService.getName() + " service</b><br/><br/>")
                                        .getBytes());
                        if (policyElements.size() != 0) {
                            String serviceContextPath = RequestProcessorUtil.getServiceContextPath(configCtx);
                            for (int i = 0; i < policyElements.size(); i++) {
                                String st = "<a href=\"" + ipAddress + serviceContextPath + "/"
                                        + axisService.getName() + "?policy&id=" + i + "\">Policy " + i
                                        + "</a><br/>";
                                outputStream.write(st.getBytes());
                            }
                        } else {
                            outputStream.write("<h4>No policies found</h4>".getBytes());
                        }
                        outputStream.write("</body></html>".getBytes());
                    }

                }
            }
        }
    } else { // Service is null
        response.addHeader(HTTP.CONTENT_TYPE, "text/html");
        outputStream
                .write(("<h4>Service " + serviceName + " not found. Cannot display policies.</h4>").getBytes());
        outputStream.flush();
    }
    outputStream.flush();
}

From source file:org.envirocar.app.network.RestClient.java

/**
 * @deprecated Use {@link DAOProvider#getSensorDAO()} / {@link SensorDAO#saveSensor(org.envirocar.app.model.Car, User)}
 * instead./*from   w  w  w  . j av a  2 s. c o  m*/
 */
@Deprecated
public static boolean createSensor(String jsonObj, String user, String token,
        AsyncHttpResponseHandler handler) {
    client.addHeader("Content-Type", "application/json");
    setHeaders(user, token);

    try {
        StringEntity se = new StringEntity(jsonObj);
        se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        client.post(null, ECApplication.BASE_URL + "/sensors", se, "application/json", handler);
    } catch (UnsupportedEncodingException e) {
        logger.warn(e.getMessage(), e);
        return false;
    }
    return true;
}

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

public void process(CarbonHttpRequest request, CarbonHttpResponse response,
        ConfigurationContext configurationContext) throws Exception {
    String requestURI = request.getRequestURI();
    String contextPath = configurationContext.getServiceContextPath();
    String serviceName = requestURI.substring(requestURI.indexOf(contextPath) + contextPath.length() + 1);

    AxisService axisService = configurationContext.getAxisConfiguration().getServiceForActivation(serviceName);
    OutputStream outputStream = response.getOutputStream();

    if (!axisService.isActive()) {
        response.addHeader(HTTP.CONTENT_TYPE, "text/html");
        outputStream.write(/*from   www  .j  a va 2s . c  om*/
                ("<h4>Service " + serviceName + " is inactive. Cannot retrieve certificate.</h4>").getBytes());
        outputStream.flush();
    } else {

        RegistryService registryService = dataHolder.getRegistryService();
        Registry registry = registryService.getConfigSystemRegistry();

        String servicePath = RegistryResources.SERVICE_GROUPS
                + axisService.getAxisServiceGroup().getServiceGroupName() + RegistryResources.SERVICES
                + axisService.getName();

        Resource serviceResource = registry.get(servicePath);
        Association[] assoc = registry.getAssociations(servicePath,
                RegistryResources.Associations.PRIVATE_KEYSTORE);

        KeyStoreManager keyStoreManager = KeyStoreManager.getInstance(MultitenantConstants.SUPER_TENANT_ID);

        KeyStore keyStore = null;
        if (assoc.length < 1) {

            boolean httpsEnabled = false;
            Association[] associations = registry.getAssociations(servicePath,
                    RegistryResources.Associations.EXPOSED_TRANSPORTS);
            for (Association association : associations) {
                Resource resource = registry.get(association.getDestinationPath());
                String transportProtocol = resource.getProperty(RegistryResources.Transports.PROTOCOL_NAME);
                if (transportProtocol.equals("https")) {
                    httpsEnabled = true;
                    break;
                }
                resource.discard();
            }

            if (httpsEnabled || Boolean.valueOf(serviceResource
                    .getProperty(RegistryResources.ServiceProperties.EXPOSED_ON_ALL_TANSPORTS))) {
                keyStore = keyStoreManager.getPrimaryKeyStore();
            }
        } else {
            KeyStore ks = null;
            String kspath = assoc[0].getDestinationPath();
            if (kspath.equals(RegistryResources.SecurityManagement.PRIMARY_KEYSTORE_PHANTOM_RESOURCE)) {
                keyStore = keyStoreManager.getPrimaryKeyStore();
            } else {
                String keyStoreName = kspath.substring(kspath.lastIndexOf('/') + 1);
                keyStore = keyStoreManager.getKeyStore(keyStoreName);
            }
        }
        serviceResource.discard();

        String alias = null;
        if (keyStore != null) {
            alias = KeyStoreUtil.getPrivateKeyAlias(keyStore);
        }

        if (alias != null) {
            Certificate cert = KeyStoreUtil.getCertificate(alias, keyStore);
            serializeCert(cert, response, outputStream, serviceName);
        } else {
            response.addHeader(HTTP.CONTENT_TYPE, "text/html");
            outputStream
                    .write(("<h4>Service " + serviceName + " does not have a private key.</h4>").getBytes());
            outputStream.flush();
        }
    }
}

From source file:org.bishoph.oxdemo.util.CreateTaskAction.java

@Override
protected JSONObject doInBackground(Object... params) {
    try {//w  ww.  j  av a2 s .  c  om
        String uri = (String) params[0];
        String title = (String) params[1];
        if (title == null && folder_id > 0) {
            Log.v("OXDemo", "Either title or folder_id missing. Done nothing!");
            return null;
        }

        Log.v("OXDemo", "Attempting to create task " + title + " on " + uri);

        JSONObject jsonobject = new JSONObject();
        jsonobject.put("folder_id", folder_id);
        jsonobject.put("title", title);
        jsonobject.put("status", 1);
        jsonobject.put("priority", 0);
        jsonobject.put("percent_completed", 0);
        jsonobject.put("recurrence_type", 0);
        jsonobject.put("private_flag", false);
        jsonobject.put("notification", false);

        Log.v("OXDemo", "Body = " + jsonobject.toString());
        HttpPut httpput = new HttpPut(uri);
        StringEntity stringentity = new StringEntity(jsonobject.toString(), HTTP.UTF_8);
        stringentity.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=UTF-8"));
        httpput.setHeader("Accept", "application/json, text/javascript");
        httpput.setHeader("Content-type", "application/json");
        httpput.setEntity(stringentity);

        HttpResponse response = httpclient.execute(httpput, localcontext);
        Log.v("OXDemo", "Created task " + title);
        HttpEntity entity = response.getEntity();
        String result = EntityUtils.toString(entity);
        Log.d("OXDemo", "<<<<<<<\n" + result + "\n\n");
        JSONObject jsonObj = new JSONObject(result);
        jsonObj.put("title", title);
        return jsonObj;
    } catch (JSONException e) {
        Log.e("OXDemo", e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.scvngr.levelup.core.net.request.factory.TicketRequestFactoryTest.java

/**
 * Tests building a support request./*from  w w w  .j av  a2s.  co  m*/
 *
 * @throws com.scvngr.levelup.core.net.AbstractRequest.BadRequestException on test failure.
 * @throws java.io.IOException on test failure.
 */
@SmallTest
public void testBuildSupportRequest() throws BadRequestException, IOException {
    final TicketRequestFactory builder = new TicketRequestFactory(getContext(), new MockAccessTokenRetriever());
    final AbstractRequest request = builder.buildSupportRequest(MESSAGE_FIXTURE);

    assertNotNull(request);
    final URL url = request.getUrl(getContext());
    assertTrue("hits /tickets endpoint", url.getPath().endsWith("/tickets"));
    assertTrue(request.getRequestHeaders(getContext()).containsKey(LevelUpRequest.HEADER_AUTHORIZATION));

    assertEquals(RequestUtils.HEADER_CONTENT_TYPE_JSON,
            request.getRequestHeaders(getContext()).get(HTTP.CONTENT_TYPE));

    assertEquals(HttpMethod.POST, request.getMethod());
    assertTrue(url.getPath().startsWith("/v14"));

    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        request.writeBodyToStream(getContext(), baos);
        assertTrue("Has expected content", baos.toString().contains(MESSAGE_FIXTURE));
    } finally {
        baos.close();
    }
}