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:com.scut.easyfe.network.kjFrame.http.HttpUtils.java

/** Returns the charset specified in the Content-Type of this header. */
public static String getCharset(HttpResponse response) {
    Header header = response.getFirstHeader(HTTP.CONTENT_TYPE);
    if (header != null) {
        String contentType = header.getValue();
        if (!TextUtils.isEmpty(contentType)) {
            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];
                    }// w  w  w.  j  a v a2s .  c  o m
                }
            }
        }
    }
    return null;
}

From source file:com.rastating.droidbeard.net.ErrorReportTask.java

public JSONObject postData(String url, JSONObject obj) {
    HttpClient client = new DefaultHttpClient();
    String json = obj.toString();

    try {//w  ww  . j  ava2  s  .c  o  m
        HttpPost post = new HttpPost(url);
        post.setHeader("Content-type", "application/json");

        StringEntity se = new StringEntity(obj.toString());
        se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
        post.setEntity(se);

        HttpResponse response = client.execute(post);
        String retval = EntityUtils.toString(response.getEntity());

        return new JSONObject(retval);
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:com.ibm.ra.remy.web.utils.BusinessRulesUtils.java

/**
 * Invoke Business Rules with JSON content
 *
 * @param content The payload of itineraries to send to Business Rules.
 * @return A JSON string representing the output of Business Rules.
 *//*  w  w  w  .  java2s.  co  m*/
public static String invokeRulesService(String json) throws Exception {
    PropertiesReader constants = PropertiesReader.getInstance();
    String username = constants.getStringProperty(USERNAME_KEY);
    String password = constants.getStringProperty(PASSWORD_KEY);
    String endpoint = constants.getStringProperty(EXECUTION_REST_URL_KEY)
            + constants.getStringProperty(RULE_APP_PATH_KEY);

    CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
    credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(username, password));
    CloseableHttpClient httpClient = HttpClientBuilder.create()
            .setDefaultCredentialsProvider(credentialsProvider).build();

    String responseString = "";

    try {
        HttpPost httpPost = new HttpPost(endpoint);
        httpPost.setHeader(HTTP.CONTENT_TYPE, ContentType.APPLICATION_JSON.toString());
        StringEntity jsonEntity = new StringEntity(json, MessageUtils.ENCODING);
        httpPost.setEntity(jsonEntity);
        CloseableHttpResponse response = httpClient.execute(httpPost);

        try {
            HttpEntity entity = response.getEntity();
            responseString = EntityUtils.toString(entity, MessageUtils.ENCODING);
            EntityUtils.consume(entity);
        } finally {
            response.close();
        }
    } finally {
        httpClient.close();
    }
    return responseString;
}

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

@Override
public void process(CarbonHttpRequest request, CarbonHttpResponse response,
        ConfigurationContext configurationContext) throws Exception {
    OutputStream outputStream = response.getOutputStream();
    response.addHeader(HTTP.CONTENT_TYPE, "text/html; charset=utf-8");
    response.addHeader("Access-Control-Allow-Origin", "*");

    Result result = new StreamResult(outputStream);
    String url = request.getParameter("resourceurl");
    url = URLEncoder.encode(url.toString(), "UTF-8");
    String contextRoot = CarbonUtils.getServerConfiguration().getFirstProperty("WebContextRoot");

    outputStream.write(("<meta content=\"text/html;charset=utf-8\" http-equiv=\"Content-Type\">\n"
            + "<meta content=\"utf-8\" http-equiv=\"encoding\">").getBytes());
    outputStream.write(//from  w  w w  .j a va  2s. c  o  m
            ("<script type='text/javascript' src='?wadl2form&contentType=text/javascript&resource=js/jquery-1.8.0.min.js'></script>")
                    .getBytes());
    outputStream.write(
            ("<script type='text/javascript' src='?wadl2form&contentType=text/javascript&resource=js/jquery.slideto.min.js'></script>")
                    .getBytes());
    outputStream.write(
            ("<script type='text/javascript' src='?wadl2form&contentType=text/javascript&resource=js/jquery.wiggle.min.js'></script>")
                    .getBytes());
    outputStream.write(
            ("<script type='text/javascript' src='?wadl2form&contentType=text/javascript&resource=js/jquery.ba-bbq.min.js'></script>")
                    .getBytes());
    outputStream.write(
            ("<script type='text/javascript' src='?wadl2form&contentType=text/javascript&resource=js/handlebars-1.0.rc.1.js'></script>")
                    .getBytes());
    outputStream.write(
            ("<script type='text/javascript' src='?wadl2form&contentType=text/javascript&resource=js/underscore-min.js'></script>")
                    .getBytes());
    outputStream.write(
            ("<script type='text/javascript' src='?wadl2form&contentType=text/javascript&resource=js/backbone-min.js'></script>")
                    .getBytes());
    outputStream.write(
            ("<script type='text/javascript' src='?wadl2form&contentType=text/javascript&resource=js/swagger.js'></script>")
                    .getBytes());
    outputStream.write(
            ("<script type='text/javascript' src='?wadl2form&contentType=text/javascript&resource=js/swagger-ui.js'></script>")
                    .getBytes());
    outputStream.write(
            ("<script type='text/javascript' src='?wadl2form&contentType=text/javascript&resource=js/jquery.base64.js'></script>")
                    .getBytes());
    outputStream.write(
            ("<link rel='stylesheet' type='text/css' href='?wadl2form&contentType=text/css&resource=css/screen.css'/>")
                    .getBytes());

    outputStream.write(("\n" + "<style type='text/css'>\n" + "    .swagger-ui-wrap {\n"
            + "        max-width: 960px;\n" + "        margin-left: auto;\n" + "        margin-right: auto;\n"
            + "    }\n" + "\n" + "    .icon-btn {\n" + "        cursor: pointer;\n" + "    }\n" + "\n"
            + "    #message-bar {\n" + "        min-height: 30px;\n" + "        text-align: center;\n"
            + "        padding-top: 10px;\n" + "    }\n" + "\n" + "    .message-success {\n"
            + "        color: #89BF04;\n" + "    }\n" + "\n" + "    .message-fail {\n"
            + "        color: #cc0000;\n" + "    }\n" + "</style>\n" + "\n"
            + "<script type='text/javascript'>\n" + "    $(function () {\n"
            + "        window.swaggerUi = new SwaggerUi({\n"
            + "            discoveryUrl: '?wadl2form&contentType=application/json&resource=swaggerurl&wadldocurl="
            + url + "',\n" + "            dom_id: 'swagger-ui-container',\n"
            + "            apiKeyName: 'authorization',\n" + "            supportHeaderParams: true,\n"
            + "            supportedSubmitMethods: ['get', 'post', 'put', 'delete', 'options'],\n"
            + "            onComplete: function (swaggerApi, swaggerUi) {\n"
            + "                if (console) {\n" + "                    console.log('Loaded SwaggerUI');\n"
            + "                    console.log(swaggerApi);\n" + "                    console.log(swaggerUi);\n"
            + "                }\n" + "                $('ul.endpoints').show();\n" + "            },\n"
            + "            onFailure: function (data) {\n" + "                if (console) {\n"
            + "                    console.log('Unable to Load SwaggerUI');\n"
            + "                    console.log(data);\n" + "                }\n" + "            },\n"
            + "            docExpansion: 'none'\n" + "        });\n" + "        window.swaggerUi.load();\n"
            + "    });\n" + "</script>\n"
            + "<div id='swagger-ui-container'>Please wait while loading try it page....</div>\n" + "<style>\n"
            + "    html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video {\n"
            + "        font-family: Arial, Helvetica, Verdana, monospace, san-serif;\n"
            + "        font-size: 12px;\n" + "        line-height: 20px;\n" + "    }\n" + "\n"
            + "    div#overview ul {\n" + "        list-style: disc;\n" + "        margin: 5px 5px 5px 18px;\n"
            + "    }\n" + "\n" + "    div#overview li {\n" + "        padding-bottom: 5px;\n" + "    }\n" + "\n"
            + "    h2 {\n" + "        font-size: 24px;\n" + "        line-height: normal;\n"
            + "        font-weight: bold;\n" + "    }\n" + "\n" + "    .search-back body {\n"
            + "        line-hieight: 18px;\n" + "    }\n" + "\n"
            + "    body ul#resources li.resource div.heading h2 a {\n" + "        color: #111111;\n" + "    }\n"
            + "\n" + "    .search-back {\n" + "        padding: 0 0 0 20px;\n" + "    }\n" + "\n"
            + "    ul.endpoints {\n" + "        padding: 10px;\n" + "        border: solid 1px #efefef;\n"
            + "    }\n" + "\n" + "    body ul#resources li.resource div.heading {\n"
            + "        background: #EFEFEF;\n" + "        padding: 0 10px;\n" + "    }\n" + "\n"
            + "    body ul#resources li.resource div.heading ul.options {\n"
            + "        margin: 23px 10px 0 0;\n" + "    }\n" + "\n" + "    h6 {\n" + "        color: inherit;\n"
            + "        font-family: inherit;\n" + "        font-weight: bold;\n"
            + "        line-height: 20px;\n" + "        margin: 0 0 10px 0;\n"
            + "        text-rendering: optimizelegibility;\n" + "    }\n" + "\n" + "    h5 {\n"
            + "        color: inherit;\n" + "        font-family: inherit;\n" + "        font-size: 18px;\n"
            + "        font-weight: bold;\n" + "        line-height: 20px;\n" + "        margin: 10px 0;\n"
            + "        text-rendering: optimizelegibility;\n" + "    }\n" + "</style>\n").getBytes());
    outputStream.write(
            ("<input type='hidden' name='contextRoot_name' id='contextRoot' value='" + contextRoot + "'>")
                    .getBytes());
    outputStream.flush();

}

From source file:com.google.developers.gdgfirenze.mockep.AndroidSimulator.java

private static void postData(String url, JSONObject jsonSamplePacket)
        throws ClientProtocolException, IOException {

    HttpParams myParams = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(myParams, 10000);
    HttpConnectionParams.setSoTimeout(myParams, 10000);
    HttpClient httpclient = new DefaultHttpClient(myParams);

    HttpPost httppost = new HttpPost(url.toString());
    httppost.setHeader("Content-type", "application/json");

    StringEntity se = new StringEntity(jsonSamplePacket.toString());
    se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
    httppost.setEntity(se);//ww  w. j  a  v a  2 s  .com

    HttpResponse response = httpclient.execute(httppost);

    String temp = EntityUtils.toString(response.getEntity());
    System.out.println("JSON post response: " + temp);
}

From source file:com.vincestyling.netroid.HttpUtils.java

/**
 * Returns the charset specified in the Content-Type of this header.
 *//*from  ww w  . j a va  2s .c  o  m*/
public static String getCharset(HttpResponse response) {
    Header header = response.getFirstHeader(HTTP.CONTENT_TYPE);
    if (header != null) {
        String contentType = header.getValue();
        if (!TextUtils.isEmpty(contentType)) {
            String[] params = contentType.split(";");
            for (int i = 1; i < params.length; i++) {
                String[] pair = params[i].trim().split("=");
                if (pair.length == 2 && pair[0].equals("charset")) {
                    return pair[1];
                }
            }
        }
    }
    return null;
}

From source file:com.mcxiaoke.next.http.entity.mime.MultipartFormEntity.java

MultipartFormEntity(final AbstractMultipartForm multipart, final String contentType, final long contentLength) {
    super();//from  w ww. jav a 2s  .  c o m
    this.multipart = multipart;
    this.contentType = new BasicHeader(HTTP.CONTENT_TYPE, contentType);
    this.contentLength = contentLength;
}

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

public static void printXsd(CarbonHttpRequest request, CarbonHttpResponse response,
        ConfigurationContext configCtx, String serviceName, AxisService axisService) throws IOException {
    if (GhostDeployerUtils.isGhostService(axisService)) {
        // if the existing service is a ghost service, deploy the actual one
        axisService = GhostDeployerUtils.deployActualService(configCtx.getAxisConfiguration(), axisService);
    }//from  ww  w. j ava  2 s .com
    if (!RequestProcessorUtil.canExposeServiceMetadata(axisService)) {
        response.setError(HttpStatus.SC_FORBIDDEN,
                "Access to service metadata for service: " + serviceName + " has been forbidden");
        return;
    }
    OutputStream outputStream = response.getOutputStream();
    String contextRoot = request.getContextPath();
    if (axisService == null) {
        response.addHeader(HTTP.CONTENT_TYPE, "text/html");
        response.setError(HttpStatus.SC_NOT_FOUND);
        outputStream.write(
                ("<h4>Service " + serviceName + " is not found. Cannot display Schema.</h4>").getBytes());
        outputStream.flush();
        return;
    }

    if (!axisService.isActive()) {
        response.addHeader(HTTP.CONTENT_TYPE, "text/html");
        outputStream
                .write(("<h4>Service " + serviceName + " is inactive. Cannot display Schema.</h4>").getBytes());
        outputStream.flush();
        return;
    }

    //cater for named xsds - check for the xsd name
    String uri = request.getQueryString();
    if (request.getQueryString().endsWith(".xsd")) {
        String schemaName = uri.substring(uri.lastIndexOf('=') + 1);

        Map services = configCtx.getAxisConfiguration().getServices();
        AxisService service = (AxisService) services.get(serviceName);
        if (service != null) {
            //run the population logic just to be sure
            service.populateSchemaMappings();
            //write out the correct schema
            Map schemaTable = service.getSchemaMappingTable();
            XmlSchema schema = (XmlSchema) schemaTable.get(schemaName);

            if (schema == null) {
                int slashIndex = schemaName.lastIndexOf('/');
                int dotIndex = schemaName.lastIndexOf('.');
                if (slashIndex > 0) {
                    String schemaKey = schemaName.substring(slashIndex + 1, dotIndex);
                    schema = (XmlSchema) schemaTable.get(schemaKey);
                }
            }

            if (schema == null) {
                int dotIndex = schemaName.indexOf('.');
                if (dotIndex > 0) {
                    String schemaKey = schemaName.substring(0, dotIndex);
                    schema = (XmlSchema) schemaTable.get(schemaKey);
                }
            }
            //schema found - write it to the stream
            if (schema != null) {
                response.setStatus(HttpStatus.SC_OK);
                response.addHeader(HTTP.CONTENT_TYPE, "text/xml");
                schema.write(response.getOutputStream());
                return;
            } else {
                InputStream instream = service.getClassLoader()
                        .getResourceAsStream(DeploymentConstants.META_INF + "/" + schemaName);

                if (instream != null) {
                    response.setStatus(HttpStatus.SC_OK);
                    response.addHeader(HTTP.CONTENT_TYPE, "text/xml");
                    OutputStream outstream = response.getOutputStream();
                    boolean checkLength = true;
                    int length = Integer.MAX_VALUE;
                    int nextValue = instream.read();
                    if (checkLength) {
                        length--;
                    }
                    while (-1 != nextValue && length >= 0) {
                        outstream.write(nextValue);
                        nextValue = instream.read();
                        if (checkLength) {
                            length--;
                        }
                    }
                    outstream.flush();
                    return;
                } else {
                    ByteArrayOutputStream baos = new ByteArrayOutputStream();
                    int ret = service.printXSD(baos, schemaName);
                    if (ret > 0) {
                        baos.flush();
                        instream = new ByteArrayInputStream(baos.toByteArray());
                        response.setStatus(HttpStatus.SC_OK);
                        response.addHeader(HTTP.CONTENT_TYPE, "text/xml");
                        OutputStream outstream = response.getOutputStream();
                        boolean checkLength = true;
                        int length = Integer.MAX_VALUE;
                        int nextValue = instream.read();
                        if (checkLength) {
                            length--;
                        }
                        while (-1 != nextValue && length >= 0) {
                            outstream.write(nextValue);
                            nextValue = instream.read();
                            if (checkLength) {
                                length--;
                            }
                        }
                        outstream.flush();
                        return;
                    }
                }
            }
        }
    }

    axisService.populateSchemaMappings();
    Map schemaMappingtable = axisService.getSchemaMappingTable();
    String xsds = request.getParameter("xsd");
    if (xsds != null && xsds.trim().length() != 0) {
        response.addHeader(HTTP.CONTENT_TYPE, "text/xml");
        XmlSchema schema = (XmlSchema) schemaMappingtable.get(xsds);
        if (schema == null) {
            int dotIndex = xsds.indexOf('.');
            if (dotIndex > 0) {
                String schemaKey = xsds.substring(0, dotIndex);
                schema = (XmlSchema) schemaMappingtable.get(schemaKey);
            }
        }
        if (schema != null) {
            //schema is there - pump it outs
            schema.write(new OutputStreamWriter(outputStream, "UTF8"));
            outputStream.flush();
            outputStream.close();
        } else if (xsds.endsWith(".xsd") && xsds.indexOf("..") == -1) {
            InputStream in = axisService.getClassLoader()
                    .getResourceAsStream(DeploymentConstants.META_INF + "/" + xsds);
            if (in != null) {
                outputStream.write(IOUtils.getStreamAsByteArray(in));
                outputStream.flush();
                outputStream.close();
            } else {
                response.setError(HttpServletResponse.SC_NOT_FOUND);
            }
        } else {
            String msg = "Invalid schema " + xsds + " requested";
            throw new IOException(msg);
        }
        return;
    }

    ArrayList schemas = axisService.getSchema();
    if (schemas.size() == 1) {
        response.addHeader(HTTP.CONTENT_TYPE, "text/xml");
        // Write to the output stream
        processSchema((XmlSchema) schemas.get(0), outputStream, contextRoot, request);

    } else {
        String idParam = request.getParameter("id");
        if (idParam != null) {
            XmlSchema schema = axisService.getSchema(Integer.parseInt(idParam));
            if (schema != null) {
                response.addHeader(HTTP.CONTENT_TYPE, "text/xml");
                processSchema(schema, outputStream, contextRoot, request);
            } else {
                response.addHeader(HTTP.CONTENT_TYPE, "text/html");
                outputStream.write("<h4>Schema not found!</h4>".getBytes());
            }
        } else {
            /*String ipAddress = "http://" + NetworkUtils.getLocalHostname() + ":" +
                ServerManager.getInstance().getHttpPort();
            String version =
                ServerConfiguration.getInstance().getFirstProperty("Version");
            outputStream.write(("<html><head>" +
                "<title>WSO2 Web Services Application Server v" +
                version +
                "Management Console" +
                " - " +
                axisService.getName() +
                " Service Schema</title>" +
                "</head>" +
                "<body>" +
                "<b>Schemas for " +
                axisService.getName() +
                " service</b><br/><br/>").getBytes());
            if (schemas.size() != 0) {
            for (int i = 0; i < schemas.size(); i++) {
                String st = "<a href=\"" + ipAddress +
                        RequestProcessorUtil.getServiceContextPath(configCtx) + "/" +
                        axisService.getName() + "?xsd&id=" + i +
                        "&" + ServerConstants.HTTPConstants.ANNOTATION + "=true" + "\">Schema " + i +
                        "</a><br/>";
                outputStream.write(st.getBytes());
            }
            } else {
            outputStream.write("<p>No schemas found</p>".getBytes());
            }
            outputStream.write("</body></html>".getBytes());*/
        }
    }
}

From source file:tk.jomp16.plugin.cyanogenmod.download.Download.java

public void download(CommandEvent commandEvent) throws IOException {
    if (commandEvent.getArgs().size() >= 1) {
        System.out.println(commandEvent.getArgs());

        DeviceInfo deviceInfo = Device.getDevices().get(commandEvent.getArgs().get(0));

        if (deviceInfo != null) {
            HttpPost httpPost = new HttpPost(CM_DOWNLOAD_API);
            StringEntity json = new StringEntity(gson.toJson(new CMApiRequest(deviceInfo.getCodename())));
            json.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            httpPost.setEntity(json);//from  ww w  .java2s. co  m
            CloseableHttpClient httpClient = HttpClients.createDefault();
            HttpContext context = new BasicHttpContext();
            HttpResponse response = httpClient.execute(httpPost, context);

            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                return;
            }

            DownloadInfo downloadInfo;

            try (BufferedReader reader = new BufferedReader(
                    new InputStreamReader(response.getEntity().getContent()))) {
                downloadInfo = gson.fromJson(reader, DownloadInfo.class);
            }

            if (downloadInfo.result.size() > 0) {
                DownloadInfo.Result latest = downloadInfo.result.get(0);
                commandEvent.respond("Latest build (" + latest.channel + ") for " + deviceInfo.getCodename()
                        + ": " + latest.url + " [md5sum: " + latest.md5sum + "]");
            } else {
                commandEvent.respond("No builds for " + deviceInfo.getCodename());
            }
        }
    }
}

From source file:com.apigee.sdk.apm.http.impl.client.cache.CacheEntity.java

public Header getContentType() {
    return this.cacheEntry.getFirstHeader(HTTP.CONTENT_TYPE);
}