Example usage for org.apache.http.entity.mime MultipartEntity MultipartEntity

List of usage examples for org.apache.http.entity.mime MultipartEntity MultipartEntity

Introduction

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

Prototype

public MultipartEntity(final HttpMultipartMode mode) 

Source Link

Usage

From source file:dk.kasperbaago.JSONHandler.JSONHandler.java

public String getURL() {

    //Making a HTTP client
    HttpClient client = new DefaultHttpClient();

    //Declaring HTTP response
    HttpResponse response = null;//  ww  w  . j  a  v a 2 s.c o m
    String myReturn = null;

    try {

        //Making a HTTP getRequest or post request
        if (method == "get") {
            String parms = "";
            if (this.parameters.size() > 0) {
                parms = "?";
                parms += URLEncodedUtils.format(this.parameters, "utf-8");
            }

            Log.i("parm", parms);
            Log.i("URL", this.url + parms);
            HttpGet getUrl = new HttpGet(this.url + parms);

            //Executing the request
            response = client.execute(getUrl);
        } else if (method == "post") {
            HttpPost getUrl = new HttpPost(this.url);

            //Sets parameters to add
            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            for (int i = 0; i < this.parameters.size(); i++) {
                if (this.parameters.get(i).getName().equalsIgnoreCase(fileField)) {
                    entity.addPart(parameters.get(i).getName(),
                            new FileBody(new File(parameters.get(i).getValue())));
                } else {
                    entity.addPart(parameters.get(i).getName(), new StringBody(parameters.get(i).getName()));
                }
            }

            getUrl.setEntity(entity);

            //Executing the request
            response = client.execute(getUrl);
        } else {
            return "false";
        }

        //Returns the data      
        HttpEntity content = response.getEntity();
        InputStream mainContent = content.getContent();
        myReturn = this.convertToString(mainContent);
        this.HTML = myReturn;
        Log.i("Result", myReturn);

    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return myReturn;
}

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;/*w w w .  j  a  va  2 s .c o m*/
    // 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.klinker.android.twitter.utils.api_helper.TwitPicHelper.java

private TwitPicStatus uploadToTwitPic() {
    try {//w  w  w  .  ja  v a2 s. c  o  m
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(POST_URL);
        post.addHeader("X-Auth-Service-Provider", SERVICE_PROVIDER);
        post.addHeader("X-Verify-Credentials-Authorization", getAuthrityHeader(twitter));

        if (file == null) {
            // only the input stream was sent, so we need to convert it to a file
            Log.v("talon_twitpic", "converting to file from input stream");
            String filePath = saveStreamTemp(stream);
            file = new File(filePath);
        } else {
            Log.v("talon_twitpic", "already have the file, going right to send it");
        }

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        entity.addPart("key", new StringBody(TWITPIC_API_KEY));
        entity.addPart("media", new FileBody(file));
        entity.addPart("message", new StringBody(message));

        Log.v("talon_twitpic", "uploading now");

        post.setEntity(entity);
        HttpResponse response = client.execute(post);
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        String line;
        String url = "";
        StringBuilder builder = new StringBuilder();
        while ((line = rd.readLine()) != null) {
            Log.v("talon_twitpic", line);
            builder.append(line);
        }

        try {
            // there is only going to be one thing returned ever
            JSONObject jsonObject = new JSONObject(builder.toString());
            url = jsonObject.getString("url");
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.v("talon_twitpic", "url: " + url);
        Log.v("talon_twitpic", "message: " + message);

        return new TwitPicStatus(message, url);
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:org.datacleaner.actions.PublishFileToMonitorActionListener.java

@Override
protected Map<?, ?> doInBackground() throws Exception {

    final MonitorConnection monitorConnection = _userPreferences.getMonitorConnection();

    final String uploadUrl = getUploadUrl(monitorConnection);
    logger.debug("Upload url: {}", uploadUrl);

    final HttpPost request = new HttpPost(uploadUrl);

    final long expectedSize = getExpectedSize();

    publish(new Task() {
        @Override//  w w w  .j a va2s  .c o m
        public void execute() throws Exception {
            _progressWindow.setExpectedSize(getTransferredFilename(), expectedSize);
        }
    });

    final MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    final ContentBody uploadFilePart = new AbstractContentBody("application/octet-stream") {

        @Override
        public String getCharset() {
            return null;
        }

        @Override
        public String getTransferEncoding() {
            return MIME.ENC_BINARY;
        }

        @Override
        public long getContentLength() {
            return expectedSize;
        }

        @Override
        public void writeTo(OutputStream out) throws IOException {
            long progress = 0;
            try (final InputStream in = getTransferStream()) {
                byte[] tmp = new byte[4096];
                int length;
                while ((length = in.read(tmp)) != -1) {
                    out.write(tmp, 0, length);

                    // update the visual progress
                    progress = progress + length;

                    final long updatedProgress = progress;

                    publish(new Task() {
                        @Override
                        public void execute() throws Exception {
                            _progressWindow.setProgress(getTransferredFilename(), updatedProgress);
                        }
                    });
                }
                out.flush();
            }
        }

        @Override
        public String getFilename() {
            return getTransferredFilename();
        }
    };

    entity.addPart("file", uploadFilePart);
    request.setEntity(entity);

    try (final MonitorHttpClient monitorHttpClient = monitorConnection.getHttpClient()) {
        final HttpResponse response;
        try {
            response = monitorHttpClient.execute(request);
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
        final StatusLine statusLine = response.getStatusLine();

        if (statusLine.getStatusCode() == 200) {
            logger.info("Upload response status: {}", statusLine);

            // parse the response as a JSON map
            final InputStream content = response.getEntity().getContent();
            final String contentString;
            try {
                contentString = FileHelper.readInputStreamAsString(content, FileHelper.DEFAULT_ENCODING);
            } finally {
                FileHelper.safeClose(content);
            }

            final ObjectMapper objectMapper = new ObjectMapper();
            try {
                final Map<?, ?> responseMap = objectMapper.readValue(contentString, Map.class);

                return responseMap;
            } catch (Exception e) {
                logger.warn("Received non-JSON response:\n{}", contentString);
                logger.error("Failed to parse response as JSON", e);
                return null;
            }
        } else {
            logger.warn("Upload response status: {}", statusLine);
            final String reasonPhrase = statusLine.getReasonPhrase();
            WidgetUtils.showErrorMessage("Server reported error",
                    "Server replied with status " + statusLine.getStatusCode() + ":\n" + reasonPhrase);
            return null;
        }
    }
}

From source file:com.servoy.extensions.plugins.http.BaseEntityEnclosingRequest.java

@Override
protected HttpEntity buildEntity() throws Exception {
    HttpEntity entity = null;//from w  w  w  .  ja v a2  s . c  o m
    if (files.size() == 0) {
        if (params != null) {
            entity = new UrlEncodedFormEntity(params, charset);
        } else if (!Utils.stringIsEmpty(content)) {
            entity = new StringEntity(content, mimeType, charset);
            content = null;
        }
    } else if (files.size() == 1 && (params == null || params.size() == 0)) {
        Object f = files.values().iterator().next();
        if (f instanceof File) {
            entity = new FileEntity((File) f, ContentType.create("binary/octet-stream")); //$NON-NLS-1$
        } else if (f instanceof JSFile) {
            entity = new InputStreamEntity(((JSFile) f).getAbstractFile().getInputStream(),
                    ((JSFile) f).js_size(), ContentType.create("binary/octet-stream")); //$NON-NLS-1$
        } else {
            Debug.error("could not add file to post request unknown type: " + f);
        }
    } else {
        entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        // For File parameters
        for (Entry<Pair<String, String>, Object> e : files.entrySet()) {
            Object file = e.getValue();
            if (file instanceof File) {
                ((MultipartEntity) entity).addPart(e.getKey().getLeft(), new FileBody((File) file));
            } else if (file instanceof JSFile) {
                ((MultipartEntity) entity).addPart(e.getKey().getLeft(),
                        new ByteArrayBody(
                                Utils.getBytesFromInputStream(
                                        ((JSFile) file).getAbstractFile().getInputStream()),
                                "binary/octet-stream", ((JSFile) file).js_getName()));
            } else {
                Debug.error("could not add file to post request unknown type: " + file);
            }
        }

        // add the parameters
        if (params != null) {
            Iterator<NameValuePair> it = params.iterator();
            while (it.hasNext()) {
                NameValuePair nvp = it.next();
                // For usual String parameters
                ((MultipartEntity) entity).addPart(nvp.getName(),
                        new StringBody(nvp.getValue(), "text/plain", Charset.forName(charset)));
            }
        }
    }

    // entity may have been set already, see PutRequest.js_setFile
    return entity;
}

From source file:ch.cyberduck.core.dropbox.client.DropboxClient.java

/**
 * Put a file in the user's Dropbox.//from  ww w .ja  v a2s. com
 */
public void put(String to, ContentBody content) throws IOException {
    HttpClient client = getClient();

    HttpPost req = (HttpPost) buildRequest(HttpPost.METHOD_NAME, "/files/" + ROOT + to, true);

    // this has to be done this way because of how oauth signs params
    // first we add a "fake" param of file=path of *uploaded* file, THEN we sign that.
    List<BasicNameValuePair> nvps = new ArrayList<BasicNameValuePair>();
    nvps.add(new BasicNameValuePair("file", content.getFilename()));
    req.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
    try {
        auth.sign(req);
    } catch (OAuthException e) {
        IOException failure = new IOException(e.getMessage());
        failure.initCause(e);
        throw failure;
    }
    // now we can add the real file multipart and we're good
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    entity.addPart("file", content);

    // this resets it to the new entity with the real file
    req.setEntity(entity);

    this.finish(client.execute(req));
}

From source file:eu.liveandgov.ar.utilities.OS_Utils.java

/**
 * Remotely recognize captured image//from w  ww  .  j a v a  2 s.co  m
 * 
 * @param url
 * @param nameValuePairs
 */
public static HttpResponse remote_rec(String url, List<NameValuePair> nameValuePairs, Context ctx) {

    HttpClient httpClient = new DefaultHttpClient();
    HttpContext localContext = new BasicHttpContext();
    HttpPost httpPost = new HttpPost(url);

    try {
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        for (int index = 0; index < nameValuePairs.size(); index++) {

            if (nameValuePairs.get(index).getName().equalsIgnoreCase("upload"))
                entity.addPart("upload", new FileBody(new File(nameValuePairs.get(index).getValue())));
            else
                entity.addPart(nameValuePairs.get(index).getName(),
                        new StringBody(nameValuePairs.get(index).getValue()));
        }

        httpPost.setEntity(entity);
        HttpResponse httpresponse = httpClient.execute(httpPost, localContext);

        return httpresponse;

    } catch (Exception e) {
        //Toast.makeText(ctx, "Can not send for recognition. Internet accessible?", Toast.LENGTH_LONG).show();
        Log.e("ERROR", "Can not send for recognition. Internet accessible?");
        return null;
    }

}

From source file:com.janoz.usenet.processors.impl.WebbasedProcessor.java

@Override
public void processNZB(NZB nzb) throws RetrieveException {
    try {//from  www .jav  a  2s  .  c  o m
        login();
        List<NameValuePair> fields = null;
        String command = null;
        if (useReportId(nzb)) {
            fields = getReportIdProps(nzb);
            command = getReportIdCommand();
        } else if (useUrl(nzb)) {
            fields = getUrlProps(nzb);
            command = getUrlCommand();
        }
        if (fields != null) {
            //Do the request            
            HttpResponse response = null;
            try {
                response = doGet(command, fields);
                validateResponse(response.getEntity().getContent());
            } finally {
                if (response != null) {
                    response.getEntity().consumeContent();
                }
            }
        } else { // no url or reportId
            //post file using POST
            fields = getFilepostOtherProps(nzb);
            command = getFilepostCommand();
            MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
            ContentBody cb = new InputStreamBody(new ByteArrayInputStream(nzb.getData()), nzb.getFilename());
            entity.addPart(getFilepostField(), cb);
            HttpResponse response = null;
            try {
                response = doPost(command, fields, entity);
                validateResponse(response.getEntity().getContent());
            } finally {
                if (response != null) {
                    response.getEntity().consumeContent();
                }
            }
        }
        logout();
    } catch (IOException e) {
        throw new RetrieveException("Error posting nzb file", e);
    }
}

From source file:com.kkbox.toolkit.internal.api.APIRequest.java

public void addMultiPartPostParam(String key, ContentBody contentBody) {
    if (multipartEntity == null) {
        multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    }/*from w  ww  .j  a  v a2  s. c  om*/
    multipartEntity.addPart(key, contentBody);
}

From source file:org.hk.jt.client.core.Request.java

private HttpResponse execPost() throws URISyntaxException, InvalidKeyException, UnsupportedEncodingException,
        NoSuchAlgorithmException, IOException {
    DefaultHttpClient client = new DefaultHttpClient();
    HttpClientParams.setCookiePolicy(client.getParams(), CookiePolicy.BROWSER_COMPATIBILITY);
    HttpPost httpPost = new HttpPost();
    httpPost.setURI(new URI(requestIf.getUrl()));
    httpPost.setHeader("Authorization", createAuthorizationValue());

    if (postParameter != null && !postParameter.isEmpty()) {
        final List<NameValuePair> params = new ArrayList<NameValuePair>();
        for (String key : postParameter.keySet()) {
            params.add(new BasicNameValuePair(key, postParameter.get(key)));
        }//from   www.  j  a  va  2 s.  c  om
        httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
    }

    if (requestIf.getFiles() != null) {
        final MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        List<NameValuePair> fileList = requestIf.getFiles();
        if (fileList != null && !fileList.isEmpty()) {
            for (NameValuePair val : fileList) {
                File file = new File(val.getValue());
                entity.addPart(val.getName(), new FileBody(file, CONTENTTYPE_BINARY));
            }
        }
        httpPost.setEntity(entity);
    }
    httpPost.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
    return client.execute(httpPost);
}