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

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

Introduction

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

Prototype

public void setContentType(Header header) 

Source Link

Usage

From source file:com.ocp.picasa.GDataClient.java

public void putStream(String feedUrl, InputStream stream, String contentType, Operation operation)
        throws IOException {
    InputStreamEntity entity = new InputStreamEntity(stream, -1);
    entity.setContentType(contentType);
    HttpPost post = new HttpPost(feedUrl);
    post.setHeader(X_HTTP_METHOD_OVERRIDE, "PUT");
    post.setEntity(entity);/*  w w  w  . j  ava2 s .c  om*/
    callMethod(post, operation);
}

From source file:com.tejus.shavedog.MediaStoreContent.java

public void handle(HttpRequest request, HttpResponse response, HttpContext context)
        throws HttpException, IOException {

    String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
    if (!method.equals("GET")) {
        throw new MethodNotSupportedException(method + " method not supported");
    }//  ww  w .  java2  s. c o  m

    String objectId = getUrlBuilder().getObjectId(request.getRequestLine().getUri());
    log.fine("GET request for object with identifier: " + objectId);

    DIDLObject obj = findObjectWithId(objectId);
    if (obj == null) {
        log.fine("Object not found, returning 404");
        response.setStatusCode(HttpStatus.SC_NOT_FOUND);
        return;
    }

    InputStream is = openDataInputStream(obj);
    if (is == null) {
        log.fine("Data not readable, returning 404");
        response.setStatusCode(HttpStatus.SC_NOT_FOUND);
        return;
    }

    long sizeInBytes = getSizeInBytes(obj);
    MimeType mimeType = getMimeType(obj);

    InputStreamEntity entity = new InputStreamEntity(is, sizeInBytes);
    entity.setContentType(mimeType.toString());
    response.setEntity(entity);
    response.setStatusCode(HttpStatus.SC_OK);
    log.fine("Streaming data bytes: " + sizeInBytes);
}

From source file:org.mahasen.thread.MahasenUploadWorker.java

public void run() {
    HttpClient uploadHttpClient = new DefaultHttpClient();

    uploadHttpClient = SSLWrapper.wrapClient(uploadHttpClient);

    if (file.exists()) {
        if (!nodeIp.equals(localIp)) {
            HttpPost httppost = new HttpPost(uri);

            try {
                InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);

                reqEntity.setContentType("binary/octet-stream");
                reqEntity.setChunked(true);
                httppost.setEntity(reqEntity);
                System.out.println("Executing Upload request " + httppost.getRequestLine());

                HttpResponse response = uploadHttpClient.execute(httppost);

                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());

                if ((response.getStatusLine().getReasonPhrase().equals("OK"))
                        && (response.getStatusLine().getStatusCode() == 200)) {
                    mahasenResource.addSplitPartStoredIp(currentPart, nodeIp);
                    PutUtil.storedNoOfParts.get(jobId).getAndIncrement();
                }/*from ww  w .  j  a  v a 2  s . c o m*/

            } catch (IOException e) {
                log.error("Error occurred in Uploading part : " + currentPart, e);
            }
        } else {
            try {
                FileInputStream inputStream = new FileInputStream(file);
                File filePart = new File(
                        MahasenConfiguration.getInstance().getRepositoryPath() + file.getName());
                FileOutputStream outputStream = new FileOutputStream(filePart);
                byte[] buffer = new byte[1024];
                int bytesRead;

                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                outputStream.flush();
                outputStream.close();
                mahasenResource.addSplitPartStoredIp(currentPart, nodeIp);
                PutUtil.storedNoOfParts.get(jobId).getAndIncrement();

            } catch (Exception e) {
                log.error("Error while storing file " + currentPart + " locally", e);
            }
        }
    }
}

From source file:com.sun.identity.proxy.client.EntityRequest.java

/**
 * Creates a new entity enclosing request for the specified incoming proxy
 * request.//from  w  w w  . j  a v a2  s .  c om
 *
 * @param request the incoming proxy request.
 */
public EntityRequest(Request request) {
    this.method = request.method;
    String contentEncoding = request.headers.first("Content-Encoding");
    int contentLength = IntegerUtil.parseInt(request.headers.first("Content-Length"), -1);
    String contentType = request.headers.first("Content-Type");
    InputStreamEntity entity = new InputStreamEntity(request.entity, contentLength);
    if (contentEncoding != null) {
        entity.setContentEncoding(contentEncoding);
    }
    if (contentType != null) {
        entity.setContentType(contentType);
    }
    setEntity(entity);
}

From source file:org.mahasen.client.Upload.java

/**
 * @param uploadFile/*www  .  j a  v a2 s. c  om*/
 * @param tags
 * @param folderStructure
 * @param addedProperties
 * @throws IOException
 */
public void upload(File uploadFile, String tags, String folderStructure, List<NameValuePair> addedProperties)
        throws IOException, MahasenClientException, URISyntaxException {
    httpclient = new DefaultHttpClient();

    if (addedProperties != null) {
        this.customProperties = addedProperties;
    }

    try {

        System.out.println(" Is Logged : " + clientLoginData.isLoggedIn());

        if (clientLoginData.isLoggedIn() == true) {

            httpclient = WebClientSSLWrapper.wrapClient(httpclient);

            File file = uploadFile;

            if (file.exists()) {

                if (!folderStructure.equals("")) {
                    customProperties.add(new BasicNameValuePair("folderStructure", folderStructure));
                }
                customProperties.add(new BasicNameValuePair("fileName", file.getName()));
                customProperties.add(new BasicNameValuePair("tags", tags));

                URI uri = URIUtils.createURI("https", clientLoginData.getHostNameAndPort(), -1,
                        "/mahasen/upload_ajaxprocessor.jsp", URLEncodedUtils.format(customProperties, "UTF-8"),
                        null);

                HttpPost httppost = new HttpPost(uri);

                InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
                reqEntity.setContentType("binary/octet-stream");
                reqEntity.setChunked(true);

                httppost.setEntity(reqEntity);

                httppost.setHeader("testHeader", "testHeadervalue");

                System.out.println("executing request " + httppost.getRequestLine());
                HttpResponse response = httpclient.execute(httppost);
                HttpEntity resEntity = response.getEntity();

                System.out.println("----------------------------------------");
                System.out.println(response.getStatusLine());

                EntityUtils.consume(resEntity);

                if (response.getStatusLine().getStatusCode() == 900) {
                    throw new MahasenClientException(String.valueOf(response.getStatusLine()));
                }

            }
        } else {
            System.out.println("User has to be logged in to perform this function");
        }
    } finally {
        httpclient.getConnectionManager().shutdown();
    }

}

From source file:com.example.testwebservice2.TestWebserviceActivity.java

private void putRequest() {
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost(URL);
    try {/*from  w w  w.ja v a2  s.  c o m*/
        byte[] b = beanConvertXml().getBytes("utf-8");
        InputStream is = new ByteArrayInputStream(b, 0, b.length);
        InputStreamEntity re = new InputStreamEntity(is, is.available());//ContentType.create(XmlContentType, WPCharset)
        re.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, XmlContentType));
        httpPost.setEntity(re);
        HttpResponse response = httpClient.execute(httpPost);
        if (response.getStatusLine().getStatusCode() == 200) {
            // getEntity 
            String result = EntityUtils.toString(response.getEntity());
            System.out.println("result:" + result);
            Toast.makeText(TestWebserviceActivity.this,
                    "result:" + response.getStatusLine().getStatusCode() + result, Toast.LENGTH_SHORT).show();
        }
        System.out.println("response   " + response.getEntity());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.fashiontec.bodyapps.sync.SyncPic.java

/**
 * Multipart put request for images.//from  w  w  w  .ja  v a 2  s. c o m
 * @param url
 * @param path
 * @return
 */
public HttpResponse put(String url, String path) {
    HttpResponse response = null;
    try {
        File file = new File(path);
        HttpClient client = new DefaultHttpClient();
        HttpPut post = new HttpPut(url);

        InputStreamEntity entity = new InputStreamEntity(new FileInputStream(file.getPath()), file.length());
        entity.setContentType("image/jpeg");
        entity.setChunked(true);
        post.setEntity(entity);

        response = client.execute(post);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return response;
}

From source file:org.fashiontec.bodyapps.sync.SyncPic.java

/**
 * Multipart post for images.//from www  .j  a  v a2  s.c  o  m
 * @param url
 * @param path
 * @return
 */
public HttpResponse post(String url, String path) {
    HttpResponse response = null;
    try {
        File file = new File(path);
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);

        InputStreamEntity entity = new InputStreamEntity(new FileInputStream(file.getPath()), file.length());
        entity.setContentType("image/jpeg");
        entity.setChunked(true);
        post.setEntity(entity);

        response = client.execute(post);
    } catch (IOException e) {
        e.printStackTrace();
    }
    return response;
}

From source file:com.phonegap.plugins.CloudStorage.java

/**
  * Executes the request and returns PluginResult.
  */*from w ww .ja v a 2s .  co  m*/
  * @param action        The action to execute.
  * @param data          JSONArry of arguments for the plugin.
  *                   'url': server url for upload
  *                   'file URI': URI of file to upload
 *                   'X-Auth-Token': authentication header to use for this request
  * @param callbackId    The callback id used when calling back into JavaScript.
  * @return              A PluginResult object with a status and message.
  * 
  */
public PluginResult execute(String action, JSONArray data, String callbackId) {
    PluginResult result = null;
    if (ACTION_UPLOAD.equals(action) || ACTION_STORE.equals(action)) {
        try {
            String serverUrl = data.get(0).toString();
            String imageURI = data.getString(1).toString();
            String token = null;
            if (ACTION_UPLOAD.equals(action)) {
                token = data.getString(2).toString();
            }

            File file = new File(new URI(imageURI));
            try {
                HttpClient httpclient = new DefaultHttpClient();

                HttpPut httpput = new HttpPut(serverUrl);

                InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
                if (ACTION_UPLOAD.equals(action)) {
                    reqEntity.setContentType("binary/octet-stream");
                    reqEntity.setChunked(true); // Send in multiple parts if needed
                } else {
                    reqEntity.setContentType("image/jpg");
                }

                httpput.setEntity(reqEntity);
                if (token != null) {
                    httpput.addHeader("X-Auth-Token", token);
                }

                HttpResponse response = httpclient.execute(httpput);
                Log.d(LOG_TAG, "http response: " + response.getStatusLine().getStatusCode()
                        + response.getStatusLine().getReasonPhrase());
                //Do something with response...
                result = new PluginResult(Status.OK, response.getStatusLine().getStatusCode());
            } catch (Exception e) {
                Log.d(LOG_TAG, e.getLocalizedMessage());
                result = new PluginResult(Status.ERROR);
            }
        } catch (JSONException e) {
            Log.d(LOG_TAG, e.getLocalizedMessage());
            result = new PluginResult(Status.JSON_EXCEPTION);
        } catch (Exception e1) {
            Log.d(LOG_TAG, e1.getLocalizedMessage());
            result = new PluginResult(Status.ERROR);
        }
    }
    return result;
}

From source file:net.sf.smbt.btc.utils.BTCResourceUtils.java

public void upload(String portID, String command, File file) {
    String query = portID + command;

    boolean verbose = true;
    boolean requestFailed = false;

    HttpResponse response;//from  ww w. jav  a  2  s . com
    HttpEntity entity;
    HttpClient httpclient = new DefaultHttpClient();

    try {
        InputStreamEntity reqEntity = new InputStreamEntity(new FileInputStream(file), -1);
        reqEntity.setContentType("application/xml");
        reqEntity.setChunked(true);

        HttpPost httpput = new HttpPost(query);
        httpput.setEntity(reqEntity);

        if (verbose) {
            System.out.println("-------- open ubibot connection --------");
            System.out.println("executing request: " + httpput.getURI());
        }

        response = httpclient.execute(httpput); // execute this mother
        entity = response.getEntity();

        String ubiResponse = "";
        String statusLine = response.getStatusLine().toString() + "\n";
        String delims = "[ ]+";
        String[] tokens = statusLine.split(delims);

        if (tokens[1].equals("200")) { // success
            System.out.println("\nserver response:");
            System.out.println(statusLine);
            ubiResponse = EntityUtils.toString(entity);
        } else { // bad request
            System.out.println("\nbad request. status code: \n");
            System.out.println(statusLine);
            System.out.println("check the HTTP status codes");
            ubiResponse = EntityUtils.toString(entity) + "\n\n";
            Header[] respHeader;
            respHeader = response.getAllHeaders();
            for (int i = 0; i < respHeader.length; i++) {
                ubiResponse += respHeader[i].toString() + "\n";
            }
            if (verbose)
                System.out.print(ubiResponse);
            requestFailed = true;
            // "***failed request***";
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        // shut down the connection manager to ensure
        // immediate deallocation of all system resources
        httpclient.getConnectionManager().shutdown();
        if (verbose) {
            System.out.println("----------- connection closed ----------\n");
        }
    }
}