Example usage for org.apache.http.entity AbstractHttpEntity setContentType

List of usage examples for org.apache.http.entity AbstractHttpEntity setContentType

Introduction

In this page you can find the example usage for org.apache.http.entity AbstractHttpEntity setContentType.

Prototype

public void setContentType(String str) 

Source Link

Usage

From source file:eu.comvantage.dataintegration.SparulSimulationServlet.java

private void simulateEvent(String eventID, String endpoint) {
    //container for the final SPARUL update command including header information
    String body = "";
    //additional body information for the SPARUL update command

    //try to encode the SPARUL update command string with UTF-8
    String temp = "";
    Gson gson = new Gson();

    //simulation of a correct request
    if (eventID.equalsIgnoreCase("sparul1")) {
        temp = "{ " + "\"Template\" : 1, " + "\"Client\" : 1, "
                + "\"Params\" : [{\"name\":\"ticket\", \"value\":\"ex:Ticket0070071239swd\"}, "
                + "{\"name\":\"person\", \"value\":\"ex:nn00110011\"}]" + "}";
    }/*  w  w  w  .  j  ava  2s .  c  o  m*/
    //simulation of invalid template id for client
    else if (eventID.equalsIgnoreCase("sparul2")) {
        temp = "{ " + "\"Template\" : 8, " + "\"Client\" : 1, "
                + "\"Params\" : [{\"name\":\"ticket\", \"value\":\"ex:Ticket008008123swd\"}, "
                + "{\"name\":\"person\", \"value\":\"ex:nn1234567\"}]" + "}";
    }
    //simulation of invalid client id
    else if (eventID.equalsIgnoreCase("sparul3")) {
        temp = "{ " + "\"Template\" : 1, " + "\"Client\" : 3, "
                + "\"Params\" : [{\"name\":\"ticket\", \"value\":\"ex:Ticket000000000swd\"}, "
                + "{\"name\":\"person\", \"value\":\"ex:nn55555\"}]" + "}";
    }
    //simulation of invalid parameter for specified template
    else if (eventID.equalsIgnoreCase("sparul4")) {
        temp = "{ " + "\"Template\" : 1, " + "\"Client\" : 1, "
                + "\"Params\" : [{\"name\":\"bla\", \"value\":\"ex:Ticket98761234swd\"}, "
                + "{\"name\":\"person\", \"value\":\"ex:nn223344\"}]" + "}";
    }
    //simulation of invalid parameter for specified template
    else if (eventID.equalsIgnoreCase("sparul5")) {
        temp = "{ " + "\"Templates\" : 1, " + "\"Clients\" : 1, "
                + "\"Param\" : [{\"name\":\"bla\", \"value\":\"ex:Ticket98761234swd\"}, "
                + "{\"name\":\"person\", \"value\":\"ex:nn223344\"}]" + "}";
    }
    //malformed json
    else if (eventID.equalsIgnoreCase("sparul6")) {
        temp = "blabla";
    }
    //simulation of a correct request
    else if (eventID.equalsIgnoreCase("sparul7")) {
        temp = "{ " + "\"Template\" : 1, " + "\"Client\" : 1, "
                + "\"Params\" : [{\"name\":\"templateId\", \"value\":\"tee:Ticket0070071239swd\"}], " + "}";
        //test of the long statement parameters of file client1_test0
    } else if (eventID.equalsIgnoreCase("sparul8")) {
        temp = "{ " + "\"Template\" : 1, " + "\"Client\" : 1, "
                + "\"Params\" : [{\"name\":\"templateId\", \"value\":\"tee:test1\"}, "
                + "{\"name\":\"reportId\", \"value\":\"1\"},"
                + "{\"name\":\"device1\", \"value\":\"tee:test2\"},"
                + "{\"name\":\"device2\", \"value\":\"tee:test3\"},"
                + "{\"name\":\"device3\", \"value\":\"tee:test4\"}]" + "}";

    }
    //body = gson.toJson(temp);
    body = temp;

    //try to execute the SPARUL update command
    try {
        //insertion is done by a manual HTTP post
        HttpPost httpPost = new HttpPost(endpoint);

        //put SPARUL update command to output stream
        ByteArrayOutputStream b_out = new ByteArrayOutputStream();
        OutputStreamWriter wr = new OutputStreamWriter(b_out);
        wr.write(body);
        wr.flush();

        //transform output stream and modify header information for HTTP post             
        byte[] bytes = b_out.toByteArray();
        AbstractHttpEntity reqEntity = new ByteArrayEntity(bytes);
        reqEntity.setContentType("application/x-www-form-urlencoded");
        reqEntity.setContentEncoding(HTTP.UTF_8);
        httpPost.setEntity(reqEntity);
        httpPost.setHeader("role", "http://www.comvantage.eu/ontologies/ac-schema/cv_wp6_comau_employee");

        HttpClient httpclient = new DefaultHttpClient();

        //          //set proxy if defined
        //            if(System.getProperty("http.proxyHost") != null) {
        //               HttpHost proxy = new HttpHost(System.getProperty("http.proxyHost"), Integer.valueOf(System.getProperty("http.proxyPort")), "http");
        //                httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
        //            }

        try {
            //execute the HTTP put
            System.out.println(
                    "SparulSimulationServlet: Event '" + eventID + "' simulated at endpoint " + endpoint);
            HttpResponse response = httpclient.execute(httpPost);

            //handle different server responses and failures
            int responseCode = response.getStatusLine().getStatusCode();
            String responseMessage = response.getStatusLine().getReasonPhrase();
            System.out.println("SparulSimulationServlet: Response = " + responseCode + ", " + responseMessage);
            //close the output stream
            wr.close();
        } catch (IOException ex) {
            throw new Exception(ex);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:br.com.bioscada.apps.biotracks.io.gdata.AndroidGDataClient.java

private HttpEntity createEntityForEntry(GDataSerializer entry, int format) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {/* www. jav a2s  .  co  m*/
        entry.serialize(baos, format);
    } catch (IOException ioe) {
        Log.e(TAG, "Unable to serialize entry.", ioe);
        throw ioe;
    } catch (ParseException pe) {
        Log.e(TAG, "Unable to serialize entry.", pe);
        throw new IOException("Unable to serialize entry: " + pe.getMessage());
    }

    byte[] entryBytes = baos.toByteArray();

    if (entryBytes != null && Log.isLoggable(TAG, Log.DEBUG)) {
        try {
            Log.d(TAG, "Serialized entry: " + new String(entryBytes, "UTF-8"));
        } catch (UnsupportedEncodingException uee) {
            // should not happen
            throw new IllegalStateException("UTF-8 should be supported!", uee);
        }
    }

    AbstractHttpEntity entity = new ByteArrayEntity(entryBytes);
    entity.setContentType(entry.getContentType());
    return entity;
}

From source file:com.ooyala.api.OoyalaApiClient.java

/**
 * Creates an instance of HttpRequestBase's subclass (HttpGet, HttpDelete, etc).
 *
 * @param methodType The HTTPMethod string name
 * @param URL        The URL//from   w ww  .  j  a  v a  2 s  .c  o  m
 * @param entity     the entity carrying the request's content
 * @return An instance of a HttpRequestBase's subclass
 */
private HttpRequestBase getHttpMethod(HttpMethodType methodType, String URL, AbstractHttpEntity entity) {
    HttpRequestBase method = null;
    entity.setContentType(contentType);

    /* create the method object */
    switch (methodType) {
    case GET:
        method = new HttpGet(URL);
        break;
    case DELETE:
        method = new HttpDelete(URL);
        break;
    case POST:
        method = new HttpPost(URL);
        ((HttpPost) method).setEntity(entity);
        break;
    case PATCH:
        method = new HttpPatch(URL);
        ((HttpPatch) method).setEntity(entity);
        break;
    case PUT:
        method = new HttpPut(URL);
        ((HttpPut) method).setEntity(entity);
        break;
    }
    return method;
}

From source file:com.nominanuda.web.http.HttpCoreHelper.java

public void setContentType(HttpResponse resp, String contentType) {
    HttpEntity e = resp.getEntity();//from www . j  a v a 2 s .  c o  m
    if (e != null && e instanceof AbstractHttpEntity) {
        AbstractHttpEntity ae = (AbstractHttpEntity) e;
        ae.setContentType(contentType);
    } else {
        resp.setHeader(HDR_CONTENT_TYPE, contentType);
    }
}

From source file:com.ooyala.api.OoyalaAPI.java

/**
 * Creates an instance of HttpRequestBase's subclass (HttpGet, HttpDelete, etc).
 * @param HTTPMethod The HTTPMethod string name
 * @param URL The URL//from   w  w  w.  j  av a  2  s. co  m
 * @param entity the entity carrying the request's content
 * @return An instance of a HttpRequestBase's subclass
 */
private HttpRequestBase getHttpMethod(String HTTPMethod, String URL, AbstractHttpEntity entity) {
    HttpRequestBase method = null;
    entity.setContentType(contentType);
    /* create the method object */
    if (HTTPMethod.toLowerCase().contentEquals("get")) {
        method = new HttpGet(URL);
    } else if (HTTPMethod.toLowerCase().contentEquals("delete")) {
        method = new HttpDelete(URL);
    } else {
        if (HTTPMethod.toLowerCase().contentEquals("post")) {
            method = new HttpPost(URL);
            ((HttpPost) method).setEntity(entity);
        } else if (HTTPMethod.toLowerCase().contentEquals("patch")) {
            method = new HttpPatch(URL);
            ((HttpPatch) method).setEntity(entity);
        } else if (HTTPMethod.toLowerCase().contentEquals("put")) {
            method = new HttpPut(URL);
            ((HttpPut) method).setEntity(entity);
        }
    }
    return method;
}

From source file:org.xmlsh.internal.commands.http.java

HttpEntity getInputEntity(Options opts) throws IOException, CoreException {

    AbstractHttpEntity entity = null;
    InputPort in = getStdin();/*from   w  w  w  .  j a v  a  2  s  . c o  m*/
    if (in.isFile())
        entity = new FileEntity(in.getFile());

    else {
        byte[] data = Util.readBytes(in.asInputStream(getSerializeOpts()));
        entity = new ByteArrayEntity(data);
    }
    // return new InputStreamEntity( in.asInputStream(mSerializeOpts),-1);
    if (opts.hasOpt("contentType"))
        entity.setContentType(opts.getOptString("contentType", "text/xml"));

    return entity;

}

From source file:org.dasein.cloud.opsource.OpSourceMethod.java

public Document invoke() throws CloudException, InternalException {
    if (logger.isTraceEnabled()) {
        logger.trace("enter - " + OpSource.class.getName() + ".invoke()");
    }/*from w ww  .  j a v  a  2 s . c  o  m*/
    try {
        URL url = null;
        try {
            url = new URL(endpoint);
        } catch (MalformedURLException e1) {
            throw new CloudException(e1);
        }
        final String host = url.getHost();
        final int urlPort = url.getPort() == -1 ? url.getDefaultPort() : url.getPort();
        final String urlStr = url.toString();

        DefaultHttpClient httpclient = new DefaultHttpClient();

        /**  HTTP Authentication */
        String uid = new String(provider.getContext().getAccessPublic());
        String pwd = new String(provider.getContext().getAccessPrivate());

        /** Type of authentication */
        List<String> authPrefs = new ArrayList<String>(2);
        authPrefs.add(AuthPolicy.BASIC);

        httpclient.getParams().setParameter("http.auth.scheme-pref", authPrefs);
        httpclient.getCredentialsProvider().setCredentials(new AuthScope(host, urlPort, null),
                new UsernamePasswordCredentials(uid, pwd));

        if (wire.isDebugEnabled()) {
            wire.debug("--------------------------------------------------------------> " + urlStr);
            wire.debug("");
        }

        AbstractHttpMessage method = this.getMethod(parameters.get(OpSource.HTTP_Method_Key), urlStr);
        method.setParams(new BasicHttpParams().setParameter(urlStr, url));
        /**  Set headers */
        method.addHeader(OpSource.Content_Type_Key, parameters.get(OpSource.Content_Type_Key));

        /** POST/PUT method specific logic */
        if (method instanceof HttpEntityEnclosingRequest) {
            HttpEntityEnclosingRequest entityEnclosingMethod = (HttpEntityEnclosingRequest) method;
            String requestBody = parameters.get(OpSource.HTTP_Post_Body_Key);

            if (requestBody != null) {
                if (wire.isDebugEnabled()) {
                    wire.debug(requestBody);
                }

                AbstractHttpEntity entity = new ByteArrayEntity(requestBody.getBytes());
                entity.setContentType(parameters.get(OpSource.Content_Type_Key));
                entityEnclosingMethod.setEntity(entity);
            } else {
                throw new CloudException("The request body is null for a post request");
            }
        }

        /** Now parse the xml */
        try {

            HttpResponse httpResponse;
            int status;
            if (wire.isDebugEnabled()) {
                for (org.apache.http.Header header : method.getAllHeaders()) {
                    wire.debug(header.getName() + ": " + header.getValue());
                }
            }
            /**  Now execute the request */
            APITrace.trace(provider, method.toString() + " " + urlStr);
            httpResponse = httpclient.execute((HttpUriRequest) method);
            status = httpResponse.getStatusLine().getStatusCode();
            if (wire.isDebugEnabled()) {
                wire.debug("invoke(): HTTP Status " + httpResponse.getStatusLine().getStatusCode() + " "
                        + httpResponse.getStatusLine().getReasonPhrase());
            }
            org.apache.http.Header[] headers = httpResponse.getAllHeaders();

            HttpEntity entity = httpResponse.getEntity();
            if (wire.isDebugEnabled()) {
                wire.debug("HTTP xml status code ---------" + status);
                for (org.apache.http.Header h : headers) {
                    if (h.getValue() != null) {
                        wire.debug(h.getName() + ": " + h.getValue().trim());
                    } else {
                        wire.debug(h.getName() + ":");
                    }
                }
                /** Can not enable this line, otherwise the entity would be empty*/
                // wire.debug("OpSource Response Body for request " + urlStr + " = " + EntityUtils.toString(entity));
                wire.debug("-----------------");
            }
            if (entity == null) {
                parseError(status, "Empty entity");
            }

            String responseBody = EntityUtils.toString(entity);

            if (status == HttpStatus.SC_OK) {
                InputStream input = null;
                try {
                    input = new ByteArrayInputStream(responseBody.getBytes("UTF-8"));
                    if (input != null) {
                        Document doc = null;
                        try {
                            doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(input);
                            if (wire.isDebugEnabled()) {
                                try {
                                    TransformerFactory transfac = TransformerFactory.newInstance();
                                    Transformer trans = transfac.newTransformer();
                                    trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                                    trans.setOutputProperty(OutputKeys.INDENT, "yes");

                                    StringWriter sw = new StringWriter();
                                    StreamResult result = new StreamResult(sw);
                                    DOMSource source = new DOMSource(doc);
                                    trans.transform(source, result);
                                    String xmlString = sw.toString();
                                    wire.debug(xmlString);
                                } catch (Exception ex) {
                                    ex.printStackTrace();
                                }
                            }
                        } catch (Exception ex) {
                            ex.printStackTrace();
                            logger.debug(ex.toString(), ex);
                        }
                        return doc;
                    }
                } catch (IOException e) {
                    logger.error(
                            "invoke(): Failed to read xml error due to a cloud I/O error: " + e.getMessage());
                    throw new CloudException(e);
                }
                /*
                catch( SAXException e ) {
                throw new CloudException(e);
                }                    
                catch( ParserConfigurationException e ) {
                throw new InternalException(e);
                }
                */
            } else if (status == HttpStatus.SC_NOT_FOUND) {
                throw new CloudException("An internal error occured: The endpoint was not found");
            } else {
                if (responseBody != null) {
                    parseError(status, responseBody);
                    Document parsedError = null;
                    if (!responseBody.contains("<HR")) {
                        parsedError = DocumentBuilderFactory.newInstance().newDocumentBuilder()
                                .parse(new ByteArrayInputStream(responseBody.getBytes("UTF-8")));
                        if (wire.isDebugEnabled()) {
                            try {
                                TransformerFactory transfac = TransformerFactory.newInstance();
                                Transformer trans = transfac.newTransformer();
                                trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
                                trans.setOutputProperty(OutputKeys.INDENT, "yes");

                                StringWriter sw = new StringWriter();
                                StreamResult result = new StreamResult(sw);
                                DOMSource source = new DOMSource(parsedError);
                                trans.transform(source, result);
                                String xmlString = sw.toString();
                                wire.debug(xmlString);
                            } catch (Exception ex) {
                                ex.printStackTrace();
                            }
                        }
                    } else
                        logger.debug("Error message was unparsable");
                    return parsedError;
                }
            }
        } catch (ParseException e) {
            throw new CloudException(e);
        } catch (SAXException e) {
            throw new CloudException(e);
        } catch (IOException e) {
            e.printStackTrace();
            throw new CloudException(e);
        } catch (ParserConfigurationException e) {
            throw new CloudException(e);
        } finally {
            httpclient.getConnectionManager().shutdown();
        }
    } finally {
        if (logger.isTraceEnabled()) {
            logger.trace("exit - " + OpSource.class.getName() + ".invoke()");
        }
        if (wire.isDebugEnabled()) {
            wire.debug("");
            wire.debug("--------------------------------------------------------------> " + endpoint);
        }
    }
    return null;
}

From source file:ti.modules.titanium.network.TiHTTPClient.java

private void handleURLEncodedData(UrlEncodedFormEntity form) {
    AbstractHttpEntity entity = null;
    if (data instanceof String) {
        try {/*  ww  w.  j  av  a2s.  c  o  m*/
            entity = new StringEntity((String) data, "UTF-8");

        } catch (Exception ex) {
            //FIXME
            Log.e(TAG, "Exception, implement recovery: ", ex);
        }
    } else if (data instanceof AbstractHttpEntity) {
        entity = (AbstractHttpEntity) data;
    } else {
        entity = form;
    }

    if (entity != null) {
        Header header = request.getFirstHeader("Content-Type");
        if (header == null) {
            entity.setContentType("application/x-www-form-urlencoded");

        } else {
            entity.setContentType(header.getValue());
        }
        HttpEntityEnclosingRequest e = (HttpEntityEnclosingRequest) request;
        e.setEntity(entity);
    }
}