Example usage for org.apache.http.entity.mime.content FileBody FileBody

List of usage examples for org.apache.http.entity.mime.content FileBody FileBody

Introduction

In this page you can find the example usage for org.apache.http.entity.mime.content FileBody FileBody.

Prototype

public FileBody(final File file) 

Source Link

Usage

From source file:foam.littlej.android.app.net.ReportsHttpClient.java

/**
 * Upload files to server 0 - success, 1 - missing parameter, 2 - invalid
 * parameter, 3 - post failed, 5 - access denied, 6 - access limited, 7 - no
 * data, 8 - api disabled, 9 - no task found, 10 - json is wrong
 *///from   w ww  .ja v a 2  s.c  o m
public boolean PostFileUpload(String URL, HashMap<String, String> params) throws IOException {
    log("PostFileUpload(): upload file to server.");

    apiUtils.updateDomain();
    entity = new MultipartEntity();
    // Dipo Fix
    try {
        // wrap try around because this constructor can throw Error
        final HttpPost httpost = new HttpPost(URL);

        if (params != null) {

            for (Entry<String, String> en : params.entrySet()) {
                String key = en.getKey();
                if (key == null || "".equals(key)) {
                    continue;
                }
                String val = en.getValue();
                if (!"filename".equals(key)) {
                    entity.addPart(key, new StringBody(val, Charset.forName("UTF-8")));
                    continue;
                }

                if (!TextUtils.isEmpty(val)) {
                    String filenames[] = val.split(",");
                    log("filenames " + ImageManager.getPhotoPath(context, filenames[0]));
                    for (int i = 0; i < filenames.length; i++) {
                        if (ImageManager.getPhotoPath(context, filenames[i]) != null) {
                            File file = new File(ImageManager.getPhotoPath(context, filenames[i]));
                            if (file.exists()) {
                                entity.addPart("incident_photo[]", new FileBody(file));
                            }
                        }
                    }
                }
            }

            // NEED THIS NOW TO FIX ERROR 417
            httpost.getParams().setBooleanParameter("http.protocol.expect-continue", false);
            httpost.setEntity(entity);

            HttpResponse response = httpClient.execute(httpost);
            Preferences.httpRunning = false;

            HttpEntity respEntity = response.getEntity();
            if (respEntity != null) {
                UshahidiApiResponse resp = GsonHelper.fromStream(respEntity.getContent(),
                        UshahidiApiResponse.class);
                return resp.getErrorCode() == 0;
            }
        }

    } catch (MalformedURLException ex) {
        log("PostFileUpload(): MalformedURLException", ex);

        return false;
        // fall through and return false
    } catch (IllegalArgumentException ex) {
        log("IllegalArgumentException", ex);
        // invalid URI
        return false;
    } catch (ConnectTimeoutException ex) {
        //connection timeout
        log("ConnectionTimeoutException");
        return false;
    } catch (SocketTimeoutException ex) {
        log("SocketTimeoutException");
    } catch (IOException e) {
        log("IOException", e);
        // timeout
        return false;
    }
    return false;
}

From source file:org.zywx.wbpalmstar.platform.push.report.PushReportHttpClient.java

public static String sendPostWithFile(String url, List<NameValuePair> nameValuePairs,
        Map<String, String> fileMap, Context mCtx) {
    HttpPost post = new HttpPost(url);
    HttpClient httpClient = getSSLHttpClient(mCtx);
    // Post???NameValuePair[]
    // ???request.getParameter("name")
    // List<NameValuePair> params = new ArrayList<NameValuePair>();
    // params.add(new BasicNameValuePair("name", data));
    // post.setHeader("Content-Type", "application/x-www-form-urlencoded");
    HttpResponse httpResponse = null;//from  w  ww  .  j a va  2 s . c om
    // HttpClient httpClient = null;
    post.setHeader("Accept", "*/*");
    try {
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        // // ?HTTP request
        for (int index = 0; index < nameValuePairs.size(); index++) {

            entity.addPart(nameValuePairs.get(index).getName(),
                    new StringBody(nameValuePairs.get(index).getValue(), Charset.forName("UTF-8")));

        }
        if (fileMap != null) {
            Iterator iterator = fileMap.entrySet().iterator();
            while (iterator.hasNext()) {
                Entry<String, String> entry = (Entry<String, String>) iterator.next();
                File file = new File(entry.getValue());
                entity.addPart(entry.getKey(), new FileBody(file));
            }
        }

        // post.setEntity(new UrlEncodedFormEntity(nameValuePairs,
        // HTTP.UTF_8));

        post.setEntity(entity);
        // ?HTTP response
        // httpClient = getSSLHttpClient();
        httpResponse = httpClient.execute(post);
        // ??200 ok
        int responesCode = httpResponse.getStatusLine().getStatusCode();
        BDebug.d("debug", "responesCode == " + responesCode);
        if (responesCode == 200) {
            // ?
            return EntityUtils.toString(httpResponse.getEntity());
        }

    } catch (ClientProtocolException e) {

        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {

        e.printStackTrace();
    } catch (Exception e) {

        e.printStackTrace();
    } finally {
        if (post != null) {
            post.abort();
            post = null;
        }
        if (httpResponse != null) {
            httpResponse = null;
        }
        if (httpClient != null) {
            httpClient.getConnectionManager().shutdown();
            httpClient = null;
        }
    }
    return null;
}

From source file:com.auditmark.jscrambler.client.JScrambler.java

private Object httpRequest(String requestMethod, String resourcePath, Map params)
        throws IOException, Exception {

    String signedData = null, urlQueryPart = null;

    if (requestMethod.toUpperCase().equals("POST") && params.isEmpty()) {
        throw new IllegalArgumentException("Parameters missing for POST request.");
    }//from w  w  w  .j av  a  2s  . c om

    String[] files = null;

    if (params == null) {
        params = new TreeMap();
    } else {
        if (params.get("files") instanceof String) {
            files = new String[] { (String) params.get("files") };
            params.put("files", files);
        } else if (params.get("files") instanceof String[]) {
            files = (String[]) params.get("files");
        }
        params = new TreeMap(params);
    }

    if (requestMethod.toUpperCase().equals("POST")) {
        signedData = signedQuery(requestMethod, resourcePath, params, null);
    } else {
        urlQueryPart = "?" + signedQuery(requestMethod, resourcePath, params, null);
    }

    // http client
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = null;

    try {
        if (signedData != null && requestMethod.toUpperCase().equals("POST")) {
            HttpPost httppost = new HttpPost(
                    apiURL() + resourcePath + (urlQueryPart != null ? urlQueryPart : ""));
            MultipartEntity reqEntity = new MultipartEntity();

            if (files != null) {
                int n = 0;
                for (String filename : files) {
                    FileBody fb = new FileBody(new File(filename));
                    reqEntity.addPart("file_" + n++, fb);
                }
            }

            for (String param : (Set<String>) params.keySet()) {
                if (param.equals("files") || param.startsWith("file_")) {
                    continue;
                }
                if (params.get(param) instanceof String) {
                    reqEntity.addPart(param, new StringBody((String) params.get(param)));
                }
            }

            httppost.setEntity(reqEntity);
            response = httpclient.execute(httppost);

        } else if (requestMethod.toUpperCase().equals("GET")) {
            HttpGet request = new HttpGet(apiURL() + resourcePath + (urlQueryPart != null ? urlQueryPart : ""));
            response = httpclient.execute(request);
        } else if (requestMethod.toUpperCase().equals("DELETE")) {
            HttpDelete request = new HttpDelete(
                    apiURL() + resourcePath + (urlQueryPart != null ? urlQueryPart : ""));
            response = httpclient.execute(request);
        } else {
            throw new Exception("Invalid request method.");
        }

        HttpEntity httpEntity = response.getEntity();

        // if GET Zip archive
        if (requestMethod.toUpperCase().equals("GET") && resourcePath.toLowerCase().endsWith(".zip")
                && response.getStatusLine().getStatusCode() == 200) {
            // Return inputstream
            return httpEntity.getContent();
        }
        // Otherwise return string
        return EntityUtils.toString(httpEntity, "UTF-8");

    } catch (IOException e) {
        throw e;
    } catch (Exception e) {
        throw e;
    }
}

From source file:com.ushahidi.android.app.net.CheckinHttpClient.java

/**
 * Upload files to server 0 - success, 1 - missing parameter, 2 - invalid
 * parameter, 3 - post failed, 5 - access denied, 6 - access limited, 7 - no
 * data, 8 - api disabled, 9 - no task found, 10 - json is wrong
 *///from   w  w w.  jav a  2  s  .  c  o  m
public boolean PostFileUpload(String URL, HashMap<String, String> params) throws IOException {
    log("PostFileUpload(): upload file to server.");

    apiUtils.updateDomain();
    entity = new MultipartEntity();
    // Dipo Fix
    try {
        // wrap try around because this constructor can throw Error
        final HttpPost httpost = new HttpPost(URL);

        if (params != null) {

            entity.addPart("task", new StringBody(params.get("task")));
            entity.addPart("action", new StringBody(params.get("action")));
            entity.addPart("mobileid", new StringBody(params.get("mobileid")));
            entity.addPart("message", new StringBody(params.get("message"), Charset.forName("UTF-8")));
            entity.addPart("lat", new StringBody(params.get("lat")));
            entity.addPart("lon", new StringBody(params.get("lon")));
            entity.addPart("firstname", new StringBody(params.get("firstname"), Charset.forName("UTF-8")));
            entity.addPart("lastname", new StringBody(params.get("lastname"), Charset.forName("UTF-8")));
            entity.addPart("email", new StringBody(params.get("email"), Charset.forName("UTF-8")));

            if (params.get("filename") != null) {
                if (!TextUtils.isEmpty(params.get("filename"))) {

                    File file = new File(ImageManager.getPhotoPath(context, params.get("filename")));

                    if (file != null) {
                        if (file.exists()) {

                            entity.addPart("photo", new FileBody(file));
                        }
                    }
                }
            }

            // NEED THIS NOW TO FIX ERROR 417
            httpost.getParams().setBooleanParameter("http.protocol.expect-continue", false);
            httpost.setEntity(entity);

            HttpResponse response = httpClient.execute(httpost);
            Preferences.httpRunning = false;

            HttpEntity respEntity = response.getEntity();
            if (respEntity != null) {
                InputStream serverInput = respEntity.getContent();
                if (serverInput != null) {
                    //TODO:: get the status confirmation code to work
                    //int status = ApiUtils
                    //.extractPayloadJSON(GetText(serverInput));

                    return true;
                }

                return false;
            }
        }

    } catch (MalformedURLException ex) {
        log("PostFileUpload(): MalformedURLException", ex);

        return false;
        // fall through and return false
    } catch (IllegalArgumentException ex) {
        log("IllegalArgumentException", ex);
        // invalid URI
        return false;
    } catch (IOException e) {
        log("IOException", e);
        // timeout
        return false;
    }
    return false;
}

From source file:edu.harvard.hul.ois.drs.pdfaconvert.clients.HttpClientIntegrationTest.java

@Test
public void doPostTest() throws URISyntaxException {
    ClassLoader loader = Thread.currentThread().getContextClassLoader();
    URL fileUrl = loader.getResource(INPUT_FILENAME);
    File inputFile = new File(fileUrl.toURI());
    assertNotNull(inputFile);//from w w w .j av  a  2  s  .  c  o m
    assertTrue(inputFile.exists());
    assertTrue(inputFile.isFile());
    assertTrue(inputFile.canRead());

    CloseableHttpClient httpclient = HttpClients.createDefault();

    HttpPost httpPost = new HttpPost(LOCAL_TOMCAT_SERVICE_URL);
    FileBody fileContent = new FileBody(inputFile);
    HttpEntity reqEntity = MultipartEntityBuilder.create().addPart(FORM_FIELD_DATAFILE, fileContent).build();
    httpPost.setEntity(reqEntity);

    CloseableHttpResponse response = null;
    try {
        logger.debug("executing request " + httpPost.getRequestLine());
        response = httpclient.execute(httpPost);
        StatusLine statusLine = response.getStatusLine();
        logger.debug("Response status line : " + statusLine);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            long len = entity.getContentLength();
            if (len != -1 && len < 2048) {
                logger.debug("len: " + len);
                logger.debug(EntityUtils.toString(entity));
            } else {
                logger.debug("len: " + len);
                Header[] allHeaders = response.getAllHeaders();
                for (Header h : allHeaders) {
                    logger.debug("Header: name:" + h.getName() + " -- value: " + h.getValue()
                            + " -- toString(): " + h);
                }
                Header header = entity.getContentEncoding();
                // logger.debug("header encoding: " + header.toString());
                header = entity.getContentType();
                logger.debug("header content type: " + header.toString());
                header = response.getFirstHeader("filename");
                String filename = header.getValue();
                String savedFilename = filename == null ? "file.pdf" : filename;
                InputStream is = entity.getContent();
                OutputStream out = new FileOutputStream("target/" + savedFilename);
                int bytesCnt;
                while ((bytesCnt = is.read()) != -1) {
                    out.write(bytesCnt);
                }
                out.close();
            }
        }
    } catch (IOException e) {
        logger.error("Something went wrong...", e);
        fail(e.getMessage());
    } finally {
        if (response != null) {
            try {
                response.close();
                httpclient.close();
            } catch (IOException e) {
                // nothing to do
                ;
            }
        }
    }
    logger.debug("DONE");

}

From source file:com.google.appinventor.components.runtime.MediaStore.java

/**
 * Asks the Web service to store the given media file.
 *
 * @param mediafile The value to store./*from   ww  w .j a va2s . com*/
 */
@SimpleFunction
public void PostMedia(String mediafile) throws FileNotFoundException {
    AsyncCallbackPair<String> myCallback = new AsyncCallbackPair<String>() {
        public void onSuccess(final String response) {
            androidUIHandler.post(new Runnable() {
                public void run() {
                    MediaStored(response);
                }
            });
        }

        public void onFailure(final String message) {
            androidUIHandler.post(new Runnable() {
                public void run() {
                    WebServiceError(message);
                }
            });
        }
    };

    try {
        HttpClient client = new DefaultHttpClient();

        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        entityBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

        String[] pathtokens = mediafile.split("/");
        String newMediaPath;

        if (pathtokens[0].equals("file:")) {
            newMediaPath = new java.io.File(new URL(mediafile).toURI()).getAbsolutePath();
        } else {
            newMediaPath = mediafile;
        }

        File media = new File(newMediaPath);
        entityBuilder.addPart("file", new FileBody(media));

        HttpEntity entity = entityBuilder.build();

        String uploadURL = getUploadUrl();
        HttpPost post = new HttpPost(uploadURL);
        post.setEntity(entity);
        HttpResponse response = client.execute(post);

        HttpEntity httpEntity = response.getEntity();
        String result = EntityUtils.toString(httpEntity);
        myCallback.onSuccess(result);
    } catch (Exception e) {
        e.printStackTrace();
        myCallback.onFailure(e.getMessage());
    }
}

From source file:com.fanfou.app.opensource.util.NetworkHelper.java

public static MultipartEntity encodeMultipartParameters(final List<SimpleRequestParam> params) {
    if (CommonHelper.isEmpty(params)) {
        return null;
    }//from  www  .  j  a  v  a 2 s.c  om
    final MultipartEntity entity = new MultipartEntity();
    try {
        for (final SimpleRequestParam param : params) {
            if (param.isFile()) {
                entity.addPart(param.getName(), new FileBody(param.getFile()));
            } else {
                entity.addPart(param.getName(), new StringBody(param.getValue(), Charset.forName(HTTP.UTF_8)));
            }
        }
    } catch (final UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return entity;
}

From source file:org.dataconservancy.ui.it.support.DepositRequest.java

public HttpPost asHttpPost() {
    if (!dataSetSet) {
        throw new IllegalStateException("DataItem not set: call setDataSet(DataItem) first.");
    }//from w w w  .  j a  v  a  2s .com

    if (fileToDeposit == null) {
        throw new IllegalStateException("File not set: call setFileToDeposit(File) first");
    }

    if (collectionId == null || collectionId.isEmpty()) {
        throw new IllegalStateException("Collection id not set: call setCollectionId(String) first.");
    }

    if (isUpdate && (dataItemIdentifier == null || dataItemIdentifier.isEmpty())) {
        throw new IllegalStateException(
                "Identifer is not set Identifier must be set: callSetDataSetIdentifier or pass in an ID in the constructor");
    }

    if (null == packageId)
        packageId = "";

    String depositUrl = urlConfig.getDepositUrl().toString()
            + "?redirectUrl=/pages/usercollections.jsp?currentCollectionId=" + collectionId;
    HttpPost post = new HttpPost(depositUrl);
    MultipartEntity entity = new MultipartEntity();
    try {
        entity.addPart("currentCollectionId", new StringBody(collectionId, Charset.forName("UTF-8")));
        entity.addPart("dataSet.name", new StringBody(name, Charset.forName("UTF-8")));
        entity.addPart("dataSet.description", new StringBody(description, Charset.forName("UTF-8")));
        entity.addPart("dataSet.id", new StringBody(dataItemIdentifier, Charset.forName("UTF-8")));
        entity.addPart("depositPackage.id", new StringBody(packageId, Charset.forName("UTF-8")));
        entity.addPart("isContainer",
                new StringBody(Boolean.valueOf(isContainer()).toString(), Charset.forName("UTF-8")));
        if (isUpdate) {
            entity.addPart("datasetToUpdateId", new StringBody(dataItemIdentifier, Charset.forName("UTF-8")));
            entity.addPart(STRIPES_UPDATE_EVENT, new StringBody("Update", Charset.forName("UTF-8")));
        } else {
            entity.addPart(STRIPES_DEPOSIT_EVENT, new StringBody("Deposit", Charset.forName("UTF-8")));
        }

    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    FileBody fileBody = new FileBody(fileToDeposit);
    entity.addPart("uploadedFile", fileBody);
    post.setEntity(entity);

    return post;
}

From source file:io.undertow.servlet.test.multipart.MultiPartTestCase.java

@Test
public void testMultiPartRequestWithAddedServlet() throws IOException {
    TestHttpClient client = new TestHttpClient();
    try {//  www  .j  a va  2  s  .  c o  m
        String uri = DefaultServer.getDefaultServerURL() + "/servletContext/added";
        HttpPost post = new HttpPost(uri);
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        entity.addPart("formValue", new StringBody("myValue", "text/plain", StandardCharsets.UTF_8));
        entity.addPart("file",
                new FileBody(new File(MultiPartTestCase.class.getResource("uploadfile.txt").getFile())));

        post.setEntity(entity);
        HttpResponse result = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        final String response = HttpClientUtils.readResponse(result);
        Assert.assertEquals("PARAMS:\n" + "name: formValue\n" + "filename: null\n" + "content-type: null\n"
                + "Content-Disposition: form-data; name=\"formValue\"\n" + "size: 7\n" + "content: myValue\n"
                + "name: file\n" + "filename: uploadfile.txt\n" + "content-type: application/octet-stream\n"
                + "Content-Disposition: form-data; name=\"file\"; filename=\"uploadfile.txt\"\n"
                + "Content-Type: application/octet-stream\n" + "size: 13\n" + "content: file contents\n",
                response);
    } finally {
        client.getConnectionManager().shutdown();
    }
}