Example usage for org.apache.http.entity.mime HttpMultipartMode BROWSER_COMPATIBLE

List of usage examples for org.apache.http.entity.mime HttpMultipartMode BROWSER_COMPATIBLE

Introduction

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

Prototype

HttpMultipartMode BROWSER_COMPATIBLE

To view the source code for org.apache.http.entity.mime HttpMultipartMode BROWSER_COMPATIBLE.

Click Source Link

Usage

From source file:org.cmuchimps.gort.modules.webinfoservice.AppEngineUpload.java

private static String uploadBlobstoreDataNoRetry(String url, String filename, String mime, byte[] data) {
    if (url == null || url.length() <= 0) {
        return null;
    }/*w  ww  . j  a  va 2  s.  c  o m*/

    if (data == null || data.length <= 0) {
        return null;
    }

    HttpClient httpClient = new DefaultHttpClient();

    HttpPost httpPost = new HttpPost(url);
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    entity.addPart("data", new ByteArrayBody(data, mime, filename));

    httpPost.setEntity(entity);

    try {
        HttpResponse response = httpClient.execute(httpPost);

        System.out.println("Blob upload status code: " + response.getStatusLine().getStatusCode());

        /*
        //http://grinder.sourceforge.net/g3/script-javadoc/HTTPClient/HTTPResponse.html
        // 2xx - success
        if (response.getStatusLine().getStatusCode() / 100 != 2) {
            return null;
        }
        */

        InputStreamReader isr = new InputStreamReader(response.getEntity().getContent());
        BufferedReader br = new BufferedReader(isr);

        String blobKey = br.readLine();

        blobKey = (blobKey != null) ? blobKey.trim() : null;

        br.close();
        isr.close();

        if (blobKey != null && blobKey.length() > 0) {
            return String.format("%s%s", MTURKSERVER_BLOB_DOWNLOAD_URL, blobKey);
        } else {
            return null;
        }

    } catch (ClientProtocolException e) {
        e.printStackTrace();
        return null;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}

From source file:MainFrame.HttpCommunicator.java

public void setCombos(JComboBox comboGroups, JComboBox comboDates, LessonTableModel tableModel)
        throws MalformedURLException, IOException {
    BufferedReader in = null;//from   w w  w  . ja  v a  2 s  .  co m
    if (SingleDataHolder.getInstance().isProxyActivated) {
        CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
        credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                SingleDataHolder.getInstance().proxyLogin, SingleDataHolder.getInstance().proxyPassword));

        HttpClient client = HttpClientBuilder.create().setDefaultCredentialsProvider(credentialsProvider)
                .build();

        HttpHost proxy = new HttpHost(SingleDataHolder.getInstance().proxyIpAdress,
                SingleDataHolder.getInstance().proxyPort);

        RequestConfig config = RequestConfig.custom().setProxy(proxy).build();

        HttpPost post = new HttpPost(SingleDataHolder.getInstance().hostAdress + "index.php");
        post.setConfig(config);

        StringBody head = new StringBody(new JSONObject().toString(), ContentType.TEXT_PLAIN);

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addPart("apideskviewer.getAllLessons", head);

        HttpEntity entity = builder.build();
        post.setEntity(entity);
        ResponseHandler<String> responseHandler = new BasicResponseHandler();
        String response = client.execute(post, responseHandler);
        System.out.println("responseBody : " + response);

        InputStream stream = new ByteArrayInputStream(response.getBytes(StandardCharsets.UTF_8));

        in = new BufferedReader(new InputStreamReader(stream));
    } else {
        URL obj = new URL(SingleDataHolder.getInstance().hostAdress);
        HttpURLConnection con = (HttpURLConnection) obj.openConnection();

        //add reuqest header
        con.setRequestMethod("POST");
        con.setRequestProperty("User-Agent", USER_AGENT);
        con.setRequestProperty("Accept-Language", "en-US,en;q=0.5");

        String urlParameters = "apideskviewer.getAllLessons={}";

        // Send post request
        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        wr.writeBytes(urlParameters);
        wr.flush();
        wr.close();

        int responseCode = con.getResponseCode();
        System.out.println("\nSending 'POST' request to URL : " + SingleDataHolder.getInstance().hostAdress);
        System.out.println("Post parameters : " + urlParameters);
        System.out.println("Response Code : " + responseCode);

        in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    }

    JSONParser parser = new JSONParser();
    try {
        Object parsedResponse = parser.parse(in);

        JSONObject jsonParsedResponse = (JSONObject) parsedResponse;

        for (int i = 0; i < jsonParsedResponse.size(); i++) {
            String s = (String) jsonParsedResponse.get(String.valueOf(i));
            String[] splittedPath = s.split("/");
            DateFormat DF = new SimpleDateFormat("yyyyMMdd");
            Date d = DF.parse(splittedPath[1].replaceAll(".bin", ""));
            Lesson lesson = new Lesson(splittedPath[0], d, false);
            String group = splittedPath[0];
            String date = new SimpleDateFormat("dd.MM.yyyy").format(d);

            if (((DefaultComboBoxModel) comboGroups.getModel()).getIndexOf(group) == -1) {
                comboGroups.addItem(group);
            }
            if (((DefaultComboBoxModel) comboDates.getModel()).getIndexOf(date) == -1) {
                comboDates.addItem(date);
            }
            tableModel.addLesson(lesson);
        }
    } catch (Exception ex) {
    }
}

From source file:org.lokra.seaweedfs.core.VolumeWrapper.java

/**
 * Upload file.//from   w  ww. j  a va2  s.c  o m
 *
 * @param url         url
 * @param fid         fid
 * @param fileName    fileName
 * @param stream      stream
 * @param ttl         ttl
 * @param contentType contentType
 * @return The size returned is the size stored on SeaweedFS.
 * @throws IOException Http connection is fail or server response within some error message.
 */
long uploadFile(String url, String fid, String fileName, InputStream stream, String ttl,
        ContentType contentType) throws IOException {
    HttpPost request;
    if (ttl != null)
        request = new HttpPost(url + "/" + fid + "?ttl=" + ttl);
    else
        request = new HttpPost(url + "/" + fid);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE).setCharset(CharsetUtils.get("UTF-8"));
    builder.addBinaryBody("upload", stream, contentType, fileName);
    HttpEntity entity = builder.build();
    request.setEntity(entity);
    JsonResponse jsonResponse = connection.fetchJsonResultByRequest(request);
    convertResponseStatusToException(jsonResponse.statusCode, url, fid, false, false, false, false);
    return (Integer) objectMapper.readValue(jsonResponse.json, Map.class).get("size");
}

From source file:com.harshad.linconnectclient.NotificationUtilities.java

public static boolean sendData(Context c, Notification n, String packageName) {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);

    ConnectivityManager connManager = (ConnectivityManager) c.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);

    // Check Wifi state, whether notifications are enabled globally, and
    // whether notifications are enabled for specific application
    if (prefs.getBoolean("pref_toggle", true) && prefs.getBoolean(packageName, true) && mWifi.isConnected()) {
        String ip = prefs.getString("pref_ip", "0.0.0.0:9090");

        // Magically extract text from notification
        ArrayList<String> notificationData = NotificationUtilities.getNotificationText(n);

        // Use PackageManager to get application name and icon
        final PackageManager pm = c.getPackageManager();
        ApplicationInfo ai;/*from w  w  w. j  a  va2  s  . c  om*/
        try {
            ai = pm.getApplicationInfo(packageName, 0);
        } catch (final NameNotFoundException e) {
            ai = null;
        }

        String notificationBody = "";
        String notificationHeader = "";
        // Create header and body of notification
        if (notificationData.size() > 0) {
            notificationHeader = notificationData.get(0);
            if (notificationData.size() > 1) {
                notificationBody = notificationData.get(1);
            }
        } else {
            return false;
        }

        for (int i = 2; i < notificationData.size(); i++) {
            notificationBody += "\n" + notificationData.get(i);
        }

        // Append application name to body
        if (pm.getApplicationLabel(ai) != null) {
            if (notificationBody.isEmpty()) {
                notificationBody = "via " + pm.getApplicationLabel(ai);
            } else {
                notificationBody += " (via " + pm.getApplicationLabel(ai) + ")";
            }
        }

        // Setup HTTP request
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        // If the notification contains an icon, use it
        if (n.largeIcon != null) {
            entity.addPart("notificon",
                    new InputStreamBody(ImageUtilities.bitmapToInputStream(n.largeIcon), "drawable.png"));
        }
        // Otherwise, use the application's icon
        else {
            entity.addPart("notificon",
                    new InputStreamBody(
                            ImageUtilities.bitmapToInputStream(
                                    ImageUtilities.drawableToBitmap(pm.getApplicationIcon(ai))),
                            "drawable.png"));
        }

        HttpPost post = new HttpPost("http://" + ip + "/notif");
        post.setEntity(entity);

        try {
            post.addHeader("notifheader", Base64.encodeToString(notificationHeader.getBytes("UTF-8"),
                    Base64.URL_SAFE | Base64.NO_WRAP));
            post.addHeader("notifdescription", Base64.encodeToString(notificationBody.getBytes("UTF-8"),
                    Base64.URL_SAFE | Base64.NO_WRAP));
        } catch (UnsupportedEncodingException e) {
            post.addHeader("notifheader",
                    Base64.encodeToString(notificationHeader.getBytes(), Base64.URL_SAFE | Base64.NO_WRAP));
            post.addHeader("notifdescription",
                    Base64.encodeToString(notificationBody.getBytes(), Base64.URL_SAFE | Base64.NO_WRAP));
        }

        // Send HTTP request
        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        try {
            response = client.execute(post);
            String html = EntityUtils.toString(response.getEntity());
            if (html.contains("true")) {
                return true;
            }
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
    return false;
}

From source file:aiai.ai.station.actors.UploadResourceActor.java

public void fixedDelay() {
    if (globals.isUnitTesting) {
        return;//w  w  w.j  a v a 2s.co  m
    }
    if (!globals.isStationEnabled) {
        return;
    }

    UploadResourceTask task;
    List<UploadResourceTask> repeat = new ArrayList<>();
    while ((task = poll()) != null) {
        boolean isOk = false;
        try (InputStream is = new FileInputStream(task.file)) {
            log.info("Start uploading result data to server, resultDataFile: {}", task.file);

            final String uri = globals.uploadRestUrl + '/' + task.taskId;
            HttpEntity entity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
                    .setCharset(StandardCharsets.UTF_8)
                    .addBinaryBody("file", is, ContentType.MULTIPART_FORM_DATA, task.file.getName()).build();

            Request request = Request.Post(uri).connectTimeout(5000).socketTimeout(5000).body(entity);

            Response response;
            if (globals.isSecureRestUrl) {
                response = executor.executor.execute(request);
            } else {
                response = request.execute();
            }
            String json = response.returnContent().asString();

            UploadResult result = fromJson(json);
            log.info("'\tresult data was successfully uploaded");
            if (!result.isOk) {
                log.error("Error uploading file, server error: " + result.error);
            }
            isOk = result.isOk;
        } catch (HttpResponseException e) {
            log.error("Error uploading code", e);
        } catch (SocketTimeoutException e) {
            log.error("SocketTimeoutException", e.toString());
        } catch (IOException e) {
            log.error("IOException", e);
        } catch (Throwable th) {
            log.error("Throwable", th);
        }
        if (!isOk) {
            log.error("'\tTask assigned one more time.");
            repeat.add(task);
        }

    }
    for (UploadResourceTask uploadResourceTask : repeat) {
        add(uploadResourceTask);
    }
}

From source file:me.ziccard.secureit.async.upload.ImagesUploaderTask.java

@Override
protected Void doInBackground(Void... params) {
    HttpClient client = new DefaultHttpClient();

    Log.i("ImagesUploaderTask", "Started");

    int imagesToUpload = 0;

    /*/*from   www  .ja  v a 2 s. c  om*/
     * If we are using mobile connectivity we upload half of the images
     * stored 
     */
    if (connectivityType == WIFI_CONNECTIVITY) {
        imagesToUpload = prefs.getMaxImages();
    }
    if (connectivityType == MOBILE_CONNECTIVITY) {
        imagesToUpload = prefs.getMaxImages() / 2;
    }
    if (connectivityType == NO_CONNECTIVITY) {
        imagesToUpload = 0;
    }

    for (int imageCount = 0; imageCount < imagesToUpload; imageCount++) {

        String path = Environment.getExternalStorageDirectory().getPath() + prefs.getImagePath() + imageCount
                + ".jpg";

        HttpPost request = new HttpPost(Remote.HOST + Remote.PHONES + "/" + phoneId + Remote.UPLOAD_IMAGES);

        Log.i("ImagesUploaderTask", "Uploading image " + path);

        /*
         * Get image from filesystem
         */
        File image = new File(path);

        //Only if the image exists we upload it 
        if (image.exists()) {

            Log.i("ImagesUploaderTask", "Image exists");

            /*
             * Getting the image from the file system
             */
            MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            reqEntity.addPart("image", new FileBody(image, "image/jpeg"));
            request.setEntity(reqEntity);

            /*
             * Setting the access token
             */
            request.setHeader("access_token", accessToken);

            try {
                HttpResponse response = client.execute(request);

                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
                StringBuilder builder = new StringBuilder();
                for (String line = null; (line = reader.readLine()) != null;) {
                    builder.append(line).append("\n");
                }

                Log.i("ImagesRecorderTask", "Response:\n" + builder.toString());

                if (response.getStatusLine().getStatusCode() != 200) {
                    throw new HttpException();
                }
            } catch (Exception e) {
                Log.e("ImageUploaderTask", "Error uploading image: " + path);
            }
            //otherwise no other image exists
        } else {
            return null;
        }
    }
    return null;
}

From source file:org.eluder.coveralls.maven.plugin.httpclient.CoverallsClient.java

public CoverallsResponse submit(final File file) throws ProcessingException, IOException {
    HttpEntity entity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
            .addBinaryBody("json_file", file, MIME_TYPE, FILE_NAME).build();
    HttpPost post = new HttpPost(coverallsUrl);
    post.setEntity(entity);/*from  ww w. j  a  v  a  2s.c o  m*/
    HttpResponse response = httpClient.execute(post);
    return parseResponse(response);
}

From source file:com.fly1tkg.streamfileupload.FileUploadFacade.java

public void post(final String url, final String fileKey, final File file, final String contentType,
        final Map<String, String> params, final FileUploadCallback callback) {

    if (null == callback) {
        throw new RuntimeException("FileUploadCallback should not be null.");
    }/*w w w.j a  v a2 s.c  o m*/

    ExecutorService executorService = Executors.newCachedThreadPool();
    executorService.execute(new Runnable() {
        public void run() {
            try {
                HttpPost httpPost = new HttpPost(url);

                FileBody fileBody;
                if (null == contentType) {
                    fileBody = new FileBody(file);
                } else {
                    fileBody = new FileBody(file, contentType);
                }

                MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                if (null == fileKey) {
                    entity.addPart(DEFAULT_FILE_KEY, fileBody);
                } else {
                    entity.addPart(fileKey, fileBody);
                }

                if (null != params) {
                    for (Map.Entry<String, String> e : params.entrySet()) {
                        entity.addPart(e.getKey(), new StringBody(e.getValue()));
                    }
                }

                httpPost.setEntity(entity);

                upload(httpPost, callback);
            } catch (UnsupportedEncodingException e) {
                callback.onFailure(-1, null, e);
            }
        }
    });
}

From source file:org.olat.test.rest.RepositoryRestClient.java

public RepositoryEntryVO deployResource(File archive, String resourcename, String displayname)
        throws URISyntaxException, IOException {
    RestConnection conn = new RestConnection(deploymentUrl);
    assertTrue(conn.login(username, password));

    URI request = UriBuilder.fromUri(deploymentUrl.toURI()).path("restapi").path("repo").path("entries")
            .build();// w w  w .j a  v a  2s .c  om
    HttpPut method = conn.createPut(request, MediaType.APPLICATION_JSON, true);
    String softKey = UUID.randomUUID().toString();
    HttpEntity entity = MultipartEntityBuilder.create().setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
            .addBinaryBody("file", archive, ContentType.APPLICATION_OCTET_STREAM, archive.getName())
            .addTextBody("filename", archive.getName()).addTextBody("resourcename", resourcename)
            .addTextBody("displayname", displayname).addTextBody("access", "3").addTextBody("softkey", softKey)
            .build();
    method.setEntity(entity);

    HttpResponse response = conn.execute(method);
    assertTrue(
            response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201);

    RepositoryEntryVO vo = conn.parse(response, RepositoryEntryVO.class);
    assertNotNull(vo);
    assertNotNull(vo.getDisplayname());
    assertNotNull(vo.getKey());
    return vo;
}