Example usage for org.apache.http.entity ByteArrayEntity ByteArrayEntity

List of usage examples for org.apache.http.entity ByteArrayEntity ByteArrayEntity

Introduction

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

Prototype

public ByteArrayEntity(byte[] bArr) 

Source Link

Usage

From source file:com.riksof.a320.http.CoreHttpClient.java

public String executePut(String url, String postMessage) throws ServerException {

    HttpParams httpParameters = new BasicHttpParams();
    HttpConnectionParams.setConnectionTimeout(httpParameters, 100000);
    HttpConnectionParams.setSoTimeout(httpParameters, 100000);

    DefaultHttpClient httpclient = new DefaultHttpClient(httpParameters);
    HttpPut httpput = new HttpPut(url);
    httpput.setHeader("Content-Type", "application/json");

    // Response String
    String responseString = null;

    try {/*from ww  w . j  a va 2 s. c o  m*/

        httpput.setEntity(new ByteArrayEntity(postMessage.toString().getBytes("UTF8")));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httpput);
        HttpEntity entity = response.getEntity();

        // Create and convert stream into string
        InputStream inStream = entity.getContent();
        responseString = convertStreamToString(inStream);

    } catch (SocketTimeoutException e) {
        // throw custom server exception in case of Exception
        Log.e("HttpClient", "Timeout Exception");
        throw new ServerException("Request Timeout");

    } catch (IOException e) {
        // throw custom server exception in case of Exception
        Log.e("HttpClient", "IO Exception");
        throw new ServerException("Request Timeout");
    }

    return responseString;
}

From source file:azkaban.utils.RestfulApiClient.java

/** helper function to fill  the request with header entries and posting body .
 * *///ww w.  j ava  2  s  . c  o  m
private static HttpEntityEnclosingRequestBase completeRequest(HttpEntityEnclosingRequestBase request,
        List<NameValuePair> headerEntries, String postingBody) throws UnsupportedEncodingException {
    if (null != completeRequest(request, headerEntries)) {
        // dump the post body UTF-8 will be used as the default encoding type.
        if (null != postingBody && postingBody.length() > 0) {
            HttpEntity entity = new ByteArrayEntity(postingBody.getBytes("UTF-8"));
            request.setHeader("Content-Length", Long.toString(entity.getContentLength()));
            request.setEntity(entity);
        }
    }
    return request;
}

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

/**
 * Sends a Request to the URL using the indicating HTTP method, content type and the array of bytes as body
 *
 * @param methodType  The HTTPMethod/*from w ww. j av  a  2 s.co  m*/
 * @param URL         The URL where the request is made
 * @param requestBody The request's body as an array of bytes
 * @return The response from the server as an object of class JSON. Must be casted to either a LinkedList<String> or an HashMap<String, Object>
 * @throws OoyalaApiException
 * @throws HttpStatusCodeException
 */
public JSON sendRequest(HttpMethodType methodType, String URL, byte[] requestBody)
        throws OoyalaApiException, HttpStatusCodeException {
    HttpRequestBase method = getHttpMethod(methodType, URL, new ByteArrayEntity(requestBody));

    try {
        return executeRequest(method);
    } catch (IOException e) {
        throw new OoyalaApiException(e);
    }
}

From source file:com.aliyun.api.gateway.demo.Client.java

private HttpEntity getEntity(Request request) {
    HttpEntity entity = null;//  w  w  w. j a  v a2  s  .c o m
    if (request.getFormBody() != null) {
        entity = buildFormEntity(request.getFormBody(), Constants.ENCODING);
    } else if (StringUtils.isNotBlank(request.getStringBody())) {
        entity = new StringEntity(request.getStringBody(), Constants.ENCODING);
    } else if (request.getBytesBody() != null) {
        entity = new ByteArrayEntity(request.getBytesBody());
    }
    return entity;
}

From source file:cn.edu.mju.Thriphoto.net.HttpManager.java

/**
 * ???? formdata name="pic"  name="file" ?????
 *
 * @param url    ?//from   w  ww. ja  v a  2  s .c  o m
 * @param method "GET" or "POST"
 * @param params ?
 * @param file   ????? SdCard ?
 *
 * @return ?
 * @throws com.sina.weibo.sdk.exception.WeiboException ?
 */
public static String uploadFile(String url, String method, WeiboParameters params, String file)
        throws WeiboException {
    String result = "";
    try {
        HttpClient client = getNewHttpClient();
        HttpUriRequest request = null;
        ByteArrayOutputStream bos = null;
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, NetStateManager.getAPN());
        if (method.equals(HTTPMETHOD_GET)) {
            url = url + "?" + Utility.encodeUrl(params);
            HttpGet get = new HttpGet(url);
            request = get;
        } else if (method.equals(HTTPMETHOD_POST)) {
            HttpPost post = new HttpPost(url);
            request = post;
            byte[] data = null;
            String _contentType = params.getValue("content-type");

            bos = new ByteArrayOutputStream();
            if (!TextUtils.isEmpty(file)) {
                paramToUpload(bos, params);
                post.setHeader("Content-Type", MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY);
                // ?
                // Utility.UploadImageUtils.revitionPostImageSize(file);
                fileToUpload(bos, file);
            } else {
                if (_contentType != null) {
                    params.remove("content-type");
                    post.setHeader("Content-Type", _contentType);
                } else {
                    post.setHeader("Content-Type", "application/x-www-form-urlencoded");
                }

                String postParam = Utility.encodeParameters(params);
                data = postParam.getBytes("UTF-8");
                bos.write(data);
            }
            data = bos.toByteArray();
            bos.close();
            ByteArrayEntity formEntity = new ByteArrayEntity(data);
            post.setEntity(formEntity);
        } else if (method.equals("DELETE")) {
            request = new HttpDelete(url);
        }
        HttpResponse response = client.execute(request);
        StatusLine status = response.getStatusLine();
        int statusCode = status.getStatusCode();

        if (statusCode != 200) {
            result = readHttpResponse(response);
            throw new WeiboHttpException(result, statusCode);
        }
        result = readHttpResponse(response);
        return result;
    } catch (IOException e) {
        throw new WeiboException(e);
    }
}

From source file:org.aludratest.service.gui.web.selenium.selenium2.AludraSeleniumHttpCommandExecutor.java

@Override
public Response execute(Command command) throws IOException {
    HttpContext context = new BasicHttpContext();

    if (command.getSessionId() == null) {
        if (QUIT.equals(command.getName())) {
            return new Response();
        }//from w  w  w  . j  a v  a2s . co m
        if (!GET_ALL_SESSIONS.equals(command.getName()) && !NEW_SESSION.equals(command.getName())) {
            throw new SessionNotFoundException("Session ID is null. Using WebDriver after calling quit()?");
        }
    }

    HttpRequest request = commandCodec.encode(command);

    String requestUrl = remoteServer.toExternalForm().replaceAll("/$", "") + request.getUri();

    HttpUriRequest httpMethod = createHttpUriRequest(request.getMethod(), requestUrl);
    for (String name : request.getHeaderNames()) {
        // Skip content length as it is implicitly set when the message entity is set below.
        if (!"Content-Length".equalsIgnoreCase(name)) {
            for (String value : request.getHeaders(name)) {
                httpMethod.addHeader(name, value);
            }
        }
    }

    if (httpMethod instanceof HttpPost) {
        ((HttpPost) httpMethod).setEntity(new ByteArrayEntity(request.getContent()));
    }

    if (requestTimeout > 0 && (httpMethod instanceof HttpRequestBase)) {
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(15000)
                .setConnectTimeout(15000).setSocketTimeout(requestTimeout).build();
        ((HttpRequestBase) httpMethod).setConfig(requestConfig);
    } else if (httpMethod instanceof HttpRequestBase) {
        // ensure Selenium Standard is set
        RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(60000)
                .setConnectTimeout(60000).setSocketTimeout(THREE_HOURS).build();
        ((HttpRequestBase) httpMethod).setConfig(requestConfig);
    }

    try {
        log(LogType.PROFILER, new HttpProfilerLogEntry(command.getName(), true));
        HttpResponse response = fallBackExecute(context, httpMethod);
        log(LogType.PROFILER, new HttpProfilerLogEntry(command.getName(), false));

        lastResponse = response;
        response = followRedirects(client, context, response, /* redirect count */0);
        lastResponse = response;

        return createResponse(response, context);
    } catch (UnsupportedCommandException e) {
        if (e.getMessage() == null || "".equals(e.getMessage())) {
            throw new UnsupportedOperationException(
                    "No information from server. Command name was: " + command.getName(), e.getCause());
        }
        throw e;
    } catch (SocketTimeoutException e) {
        LoggerFactory.getLogger(AludraSeleniumHttpCommandExecutor.class)
                .warn("Timeout in HTTP Command Executor. Timeout was "
                        + ((HttpRequestBase) httpMethod).getConfig().getSocketTimeout());
        throw e;
    }
}

From source file:org.jupnp.transport.impl.apache.StreamClientImpl.java

protected HttpEntity createHttpRequestEntity(UpnpMessage upnpMessage) {
    if (upnpMessage.getBodyType().equals(UpnpMessage.BodyType.BYTES)) {
        if (log.isLoggable(Level.FINE))
            log.fine("Preparing HTTP request entity as byte[]");
        return new ByteArrayEntity(upnpMessage.getBodyBytes());
    } else {//from   w  w  w. jav  a2s  . c  o m
        if (log.isLoggable(Level.FINE))
            log.fine("Preparing HTTP request entity as string");
        try {
            String charset = upnpMessage.getContentTypeCharset();
            return new StringEntity(upnpMessage.getBodyString(), charset != null ? charset : "UTF-8");
        } catch (Exception ex) {
            // WTF else am I supposed to do with this exception?
            throw new RuntimeException(ex);
        }
    }
}

From source file:com.easyhome.common.modules.network.HttpManager.java

/**
 * ???? formdata name="pic"  name="file" ?????
 * /*w w w .ja  v a  2s.  c  om*/
 * @param url    ?
 * @param method "GET" or "POST"
 * @param params ?
 * @param file   ????? SdCard ?
 * 
 * @return ?
 * @throws com.sina.weibo.sdk.exception.WeiboException ?
 */
public static String uploadFile(String url, String method, WeiboParameters params, String file)
        throws WeiboException {
    String result = "";
    try {
        HttpClient client = getNewHttpClient();
        HttpUriRequest request = null;
        ByteArrayOutputStream bos = null;
        client.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, NetStateManager.getAPN());
        if (method.equals(HTTPMETHOD_GET)) {
            url = url + "?" + Utility.encodeUrl(params);
            HttpGet get = new HttpGet(url);
            request = get;
        } else if (method.equals(HTTPMETHOD_POST)) {
            HttpPost post = new HttpPost(url);
            request = post;
            byte[] data = null;
            String _contentType = params.getValue("content-type");

            bos = new ByteArrayOutputStream();
            if (!TextUtils.isEmpty(file)) {
                paramToUpload(bos, params);
                post.setHeader("Content-Type", MULTIPART_FORM_DATA + "; boundary=" + BOUNDARY);
                // ?
                // Utility.UploadImageUtils.revitionPostImageSize(file);
                fileToUpload(bos, file);
            } else {
                if (_contentType != null) {
                    params.remove("content-type");
                    post.setHeader("Content-Type", _contentType);
                } else {
                    post.setHeader("Content-Type", "application/x-www-form-urlencoded");
                }

                String postParam = Utility.encodeParameters(params);
                data = postParam.getBytes("UTF-8");
                bos.write(data);
            }
            data = bos.toByteArray();
            bos.close();
            ByteArrayEntity formEntity = new ByteArrayEntity(data);
            post.setEntity(formEntity);
        } else if (method.equals("DELETE")) {
            request = new HttpDelete(url);
        }
        HttpResponse response = client.execute(request);
        StatusLine status = response.getStatusLine();
        int statusCode = status.getStatusCode();

        if (statusCode != 200) {
            result = readHttpResponse(response);
            throw new WeiboException(result);
        }
        result = readHttpResponse(response);
        return result;
    } catch (IOException e) {
        throw new WeiboException(e);
    }
}

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  w  w.j a v  a2  s .c om*/
    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;
}