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

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

Introduction

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

Prototype

public void addPart(final String name, final ContentBody contentBody) 

Source Link

Usage

From source file:com.wishlist.Wishlist.java

public void uploadPhoto() {
    uploadCancelled = false;/*from   w w w  .  j a  va 2  s .  co  m*/
    dialog = ProgressDialog.show(Wishlist.this, "", getString(R.string.uploading_photo), true, true,
            new DialogInterface.OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    uploadCancelled = true;
                }
            });

    /*
     * Upload photo to the server in a new thread
     */
    new Thread() {
        public void run() {
            try {
                String postURL = HOST_SERVER_URL + HOST_PHOTO_UPLOAD_URI;

                HttpClient httpClient = new DefaultHttpClient();
                HttpPost postRequest = new HttpPost(postURL);

                ByteArrayBody bab = new ByteArrayBody(imageBytes, "file_name_ignored");
                MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                reqEntity.addPart("source", bab);
                postRequest.setEntity(reqEntity);

                HttpResponse response = httpClient.execute(postRequest);
                BufferedReader reader = new BufferedReader(
                        new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
                String sResponse;
                StringBuilder s = new StringBuilder();
                while ((sResponse = reader.readLine()) != null) {
                    s = s.append(sResponse);
                }
                /*
                 * JSONObject is returned with image_name and image_url
                 */
                JSONObject jsonResponse = new JSONObject(s.toString());
                mProductImageName = jsonResponse.getString("image_name");
                mProductImageURL = jsonResponse.getString("image_url");
                dismissDialog();
                if (mProductImageName == null) {
                    showToast(getString(R.string.error_uploading_photo));
                    return;
                }
                /*
                 * photo upload finish, now publish to the timeline
                 */
                if (!uploadCancelled) {
                    mHandler.post(new Runnable() {
                        public void run() {
                            addToTimeline();
                        }
                    });
                }
            } catch (Exception e) {
                Log.e(e.getClass().getName(), e.getMessage());
            }
        }
    }.start();
}

From source file:info.ajaxplorer.client.http.RestRequest.java

private HttpResponse issueRequest(URI uri, Map<String, String> postParameters, File file, String fileName,
        AjxpFileBody fileBody) throws Exception {
    URI originalUri = new URI(uri.toString());
    if (RestStateHolder.getInstance().getSECURE_TOKEN() != null) {
        uri = new URI(
                uri.toString().concat("&secure_token=" + RestStateHolder.getInstance().getSECURE_TOKEN()));
    }//from w w w  . j  av  a 2 s  .  c  o  m
    //Log.d("RestRequest", "Issuing request : " + uri.toString());
    HttpResponse response = null;
    try {
        HttpRequestBase request;

        if (postParameters != null || file != null) {
            request = new HttpPost();
            if (file != null) {

                if (fileBody == null) {
                    if (fileName == null)
                        fileName = file.getName();
                    fileBody = new AjxpFileBody(file, fileName);
                    ProgressListener origPL = this.uploadListener;
                    Map<String, String> caps = RestStateHolder.getInstance().getServer()
                            .getRemoteCapacities(this);
                    this.uploadListener = origPL;
                    int maxUpload = 0;
                    if (caps != null && caps.containsKey(Server.capacity_UPLOAD_LIMIT))
                        maxUpload = new Integer(caps.get(Server.capacity_UPLOAD_LIMIT));
                    maxUpload = Math.min(maxUpload, 60000000);
                    if (maxUpload > 0 && maxUpload < file.length()) {
                        fileBody.chunkIntoPieces(maxUpload);
                        if (uploadListener != null) {
                            uploadListener.partTransferred(fileBody.getCurrentIndex(),
                                    fileBody.getTotalChunks());
                        }
                    }
                } else {
                    if (uploadListener != null) {
                        uploadListener.partTransferred(fileBody.getCurrentIndex(), fileBody.getTotalChunks());
                    }
                }
                MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                reqEntity.addPart("userfile_0", fileBody);

                if (fileName != null && !EncodingUtils
                        .getAsciiString(EncodingUtils.getBytes(fileName, "US-ASCII")).equals(fileName)) {
                    reqEntity.addPart("urlencoded_filename",
                            new StringBody(java.net.URLEncoder.encode(fileName, "UTF-8")));
                }
                if (fileBody != null && !fileBody.getFilename().equals(fileBody.getRootFilename())) {
                    reqEntity.addPart("appendto_urlencoded_part",
                            new StringBody(java.net.URLEncoder.encode(fileBody.getRootFilename(), "UTF-8")));
                }
                if (postParameters != null) {
                    Iterator<Map.Entry<String, String>> it = postParameters.entrySet().iterator();
                    while (it.hasNext()) {
                        Map.Entry<String, String> entry = it.next();
                        reqEntity.addPart(entry.getKey(), new StringBody(entry.getValue()));
                    }
                }
                if (uploadListener != null) {
                    CountingMultipartRequestEntity countingEntity = new CountingMultipartRequestEntity(
                            reqEntity, uploadListener);
                    ((HttpPost) request).setEntity(countingEntity);
                } else {
                    ((HttpPost) request).setEntity(reqEntity);
                }
            } else {
                List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(postParameters.size());
                Iterator<Map.Entry<String, String>> it = postParameters.entrySet().iterator();
                while (it.hasNext()) {
                    Map.Entry<String, String> entry = it.next();
                    nameValuePairs.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                }
                ((HttpPost) request).setEntity(new UrlEncodedFormEntity(nameValuePairs));
            }
        } else {
            request = new HttpGet();
        }

        request.setURI(uri);
        if (this.httpUser.length() > 0 && this.httpPassword.length() > 0) {
            request.addHeader("Ajxp-Force-Login", "true");
        }
        response = httpClient.executeInContext(request);
        if (isAuthenticationRequested(response)) {
            sendMessageToHandler(MessageListener.MESSAGE_WHAT_STATE, STATUS_REFRESHING_AUTH);
            this.discardResponse(response);
            this.authenticate();
            if (loginStateChanged) {
                // RELOAD
                loginStateChanged = false;
                sendMessageToHandler(MessageListener.MESSAGE_WHAT_STATE, STATUS_LOADING_DATA);
                if (fileBody != null)
                    fileBody.resetChunkIndex();
                return this.issueRequest(originalUri, postParameters, file, fileName, fileBody);
            }
        } else if (fileBody != null && fileBody.isChunked() && !fileBody.allChunksUploaded()) {
            this.discardResponse(response);
            this.issueRequest(originalUri, postParameters, file, fileName, fileBody);
        }
    } catch (ClientProtocolException e) {
        sendMessageToHandler(MessageListener.MESSAGE_WHAT_ERROR, e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        sendMessageToHandler(MessageListener.MESSAGE_WHAT_ERROR, e.getMessage());
        e.printStackTrace();
    } catch (AuthenticationException e) {
        sendMessageToHandler(MessageListener.MESSAGE_WHAT_ERROR, e.getMessage());
        throw e;
    } catch (Exception e) {
        sendMessageToHandler(MessageListener.MESSAGE_WHAT_ERROR, e.getMessage());
        e.printStackTrace();
    } finally {
        uploadListener = null;
    }
    return response;
}

From source file:com.starclub.enrique.BuyActivity.java

public void updateCredit(int credit) {

    progress = new ProgressDialog(this);
    progress.setCancelable(false);//from w ww. j av  a 2 s  . co  m
    progress.setMessage("Updating...");

    progress.show();

    m_nCredit = credit;

    new Thread() {
        public void run() {

            HttpParams myParams = new BasicHttpParams();

            HttpConnectionParams.setConnectionTimeout(myParams, 30000);
            HttpConnectionParams.setSoTimeout(myParams, 30000);

            DefaultHttpClient hc = new DefaultHttpClient(myParams);
            ResponseHandler<String> res = new BasicResponseHandler();

            String url = Utils.getUpdateUrl();
            HttpPost postMethod = new HttpPost(url);

            String responseBody = "";
            try {
                MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

                reqEntity.addPart("cid", new StringBody("" + MyConstants.CID));
                reqEntity.addPart("token", new StringBody("" + Utils.getUserToken()));
                reqEntity.addPart("user_id", new StringBody("" + Utils.getUserID()));

                reqEntity.addPart("credit", new StringBody("" + m_nCredit));

                postMethod.setEntity(reqEntity);
                responseBody = hc.execute(postMethod, res);

                System.out.println("update result = " + responseBody);
                JSONObject result = new JSONObject(responseBody);
                if (result != null) {
                    boolean status = result.optBoolean("status");
                    if (status) {

                        m_handler.sendEmptyMessage(1);

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

            m_handler.sendEmptyMessage(-1);
        }
    }.start();
}

From source file:com.iia.giveastick.util.RestClient.java

private HttpEntity buildMultipartEntity(JSONObject jsonParams) {
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    try {// ww w . j a v  a2s.c  om
        String path = jsonParams.getString("file");

        if (debugWeb && GiveastickApplication.DEBUG) {
            Log.d(TAG, "key : file value :" + path);
        }

        if (!TextUtils.isEmpty(path)) {
            // File entry
            File file = new File(path);
            FileBody fileBin = new FileBody(file, "application/octet");
            entity.addPart("file", fileBin);

            try {
                entity.addPart("file", new StringBody(path, "text/plain", Charset.forName(HTTP.UTF_8)));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                Log.e(TAG, e.getMessage());
            }
        }
    } catch (JSONException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    return entity;
}

From source file:fr.mael.jiwigo.dao.impl.ImageDaoImpl.java

public void addSimple(File file, Integer category, String title, Integer level) throws JiwigoException {
    HttpPost httpMethod = new HttpPost(((SessionManagerImpl) sessionManager).getUrl());

    //   nameValuePairs.add(new BasicNameValuePair("method", "pwg.images.addSimple"));
    //   for (int i = 0; i < parametres.length; i += 2) {
    //       nameValuePairs.add(new BasicNameValuePair(parametres[i], parametres[i + 1]));
    //   }//from www .  j a  va2s  .  com
    //   method.setEntity(new UrlEncodedFormEntity(nameValuePairs));

    if (file != null) {
        MultipartEntity multipartEntity = new MultipartEntity();

        //      String string = nameValuePairs.toString();
        // dirty fix to remove the enclosing entity{}
        //      String substring = string.substring(string.indexOf("{"),
        //            string.lastIndexOf("}") + 1);
        try {
            multipartEntity.addPart("method", new StringBody(MethodsEnum.ADD_SIMPLE.getLabel()));
            multipartEntity.addPart("category", new StringBody(category.toString()));
            multipartEntity.addPart("name", new StringBody(title));
            if (level != null) {
                multipartEntity.addPart("level", new StringBody(level.toString()));
            }
        } catch (UnsupportedEncodingException e) {
            throw new JiwigoException(e);
        }

        //      StringBody contentBody = new StringBody(substring,
        //            Charset.forName("UTF-8"));
        //      multipartEntity.addPart("entity", contentBody);
        FileBody fileBody = new FileBody(file);
        multipartEntity.addPart("image", fileBody);
        ((HttpPost) httpMethod).setEntity(multipartEntity);
    }

    HttpResponse response;
    StringBuilder sb = new StringBuilder();
    try {
        response = ((SessionManagerImpl) sessionManager).getClient().execute(httpMethod);

        int responseStatusCode = response.getStatusLine().getStatusCode();

        switch (responseStatusCode) {
        case HttpURLConnection.HTTP_CREATED:
            break;
        case HttpURLConnection.HTTP_OK:
            break;
        case HttpURLConnection.HTTP_BAD_REQUEST:
            throw new JiwigoException("status code was : " + responseStatusCode);
        case HttpURLConnection.HTTP_FORBIDDEN:
            throw new JiwigoException("status code was : " + responseStatusCode);
        case HttpURLConnection.HTTP_NOT_FOUND:
            throw new JiwigoException("status code was : " + responseStatusCode);
        default:
            throw new JiwigoException("status code was : " + responseStatusCode);
        }

        HttpEntity resultEntity = response.getEntity();
        BufferedHttpEntity responseEntity = new BufferedHttpEntity(resultEntity);

        BufferedReader reader = new BufferedReader(new InputStreamReader(responseEntity.getContent()));
        String line;

        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append("\n");
            }
        } finally {
            reader.close();
        }
    } catch (ClientProtocolException e) {
        throw new JiwigoException(e);
    } catch (IOException e) {
        throw new JiwigoException(e);
    }
    String stringResult = sb.toString();

}

From source file:org.bungeni.ext.integration.bungeniportal.BungeniAppConnector.java

public WebResponse multipartPostUrl(String sPage, boolean prefix, List<BasicNameValuePair> nameValuePairs)
        throws UnsupportedEncodingException {
    WebResponse wr = null;// w  ww. jav  a 2 s  . c  o m
    String pageURL = (prefix ? this.urlBase + sPage : sPage);
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    for (BasicNameValuePair nv : nameValuePairs) {
        entity.addPart(nv.getName(), new StringBody(nv.getValue()));
    }

    return this.doMultiPartPost(pageURL, entity);
    /*
    HttpPost webPost = new HttpPost(pageURL);
    webPost.setEntity(entity);
    HttpResponse response = null ;
    try {
    response = client.execute(webPost);
    ResponseHandler<String> responseHandler = new BasicResponseHandler();
    String sBody = responseHandler.handleResponse(response);
    wr = new WebResponse(response.getStatusLine().getStatusCode(), sBody);
    } catch (IOException ex) {
    log.error(ex.getMessage(), ex);
    } finally {
    if (response != null) {
        consumeContent(
            response.getEntity()
        );
    }
    }
    return wr; */
}

From source file:org.openremote.modeler.service.impl.ResourceServiceImpl.java

public void saveTemplateResourcesToBeehive(Template template) {
    boolean share = template.getShareTo() == Template.PUBLIC;
    HttpClient httpClient = new DefaultHttpClient();
    HttpPost httpPost = new HttpPost();
    String beehiveRootRestURL = configuration.getBeehiveRESTRootUrl();
    String url = "";
    if (!share) {
        url = beehiveRootRestURL + "account/" + userService.getAccount().getOid() + "/template/"
                + template.getOid() + "/resource/";
    } else {//from   w w w .j  ava2  s  .c  o m
        url = beehiveRootRestURL + "account/0/template/" + template.getOid() + "/resource/";
    }
    try {
        httpPost.setURI(new URI(url));
        File templateZip = getTemplateResource(template);
        if (templateZip == null) {
            serviceLog.warn("There are no template resources for template \"" + template.getName()
                    + "\"to save to beehive!");
            return;
        }
        FileBody resource = new FileBody(templateZip);
        MultipartEntity entity = new MultipartEntity();
        entity.addPart("resource", resource);

        this.addAuthentication(httpPost);
        httpPost.setEntity(entity);

        HttpResponse response = httpClient.execute(httpPost);

        if (200 != response.getStatusLine().getStatusCode()) {
            throw new BeehiveNotAvailableException("Failed to save template to Beehive, status code: "
                    + response.getStatusLine().getStatusCode());
        }
    } catch (NullPointerException e) {
        serviceLog.warn("There are no template resources for template \"" + template.getName()
                + "\"to save to beehive!");
    } catch (IOException e) {
        throw new BeehiveNotAvailableException("Failed to save template to Beehive", e);
    } catch (URISyntaxException e) {
        throw new IllegalRestUrlException(
                "Invalid Rest URL: " + url + " to save template resource to beehive! ", e);
    }
}

From source file:palamarchuk.smartlife.app.RegisterActivity.java

private void startRegisterProcess(String deviceKey) {
    String url = ServerRequest.DOMAIN + "/users";
    MultipartEntity multipartEntity;

    // collect data
    try {//from   ww  w . j ava  2s  . c  o  m
        multipartEntity = collectData();
        multipartEntity.addPart("token", new StringBody(deviceKey));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
        throw new RuntimeException(e);
    }
    QueryMaster queryMaster = new QueryMaster(RegisterActivity.this, url, QueryMaster.QUERY_POST,
            multipartEntity);
    queryMaster.setProgressDialog();

    queryMaster.setOnCompleteListener(new QueryMaster.OnCompleteListener() {
        @Override
        public void complete(String serverResponse) {
            try {
                JSONObject jsonObject = new JSONObject(serverResponse);
                String status = jsonObject.getString("status");

                if (status.equalsIgnoreCase(ServerRequest.STATUS_SUCCESS)) {
                    Toast.makeText(RegisterActivity.this, "??  ?",
                            Toast.LENGTH_SHORT).show();

                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString(SHARED_PREF_PHONE, phone.getText().toString());
                    editor.putString(SHARED_PREF_PASSWORD, password.getText().toString());
                    editor.apply();

                    AlertDialog.Builder builder = new AlertDialog.Builder(RegisterActivity.this);
                    builder.setMessage(
                            "?      ?? ?,    ");
                    builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //                                startLoginActivityAutoStart(RegisterActivity.this);
                            Intent loginActivity = new Intent(RegisterActivity.this, LoginActivity.class);
                            loginActivity.putExtra(LoginActivity.SMS_VERIFICATION, true);
                            loginActivity.putExtra(LoginActivity.AUTOLOGIN, true);

                            startActivity(loginActivity);
                            finish();
                        }
                    });
                    builder.show();

                } else if (status.equalsIgnoreCase(ServerRequest.STATUS_ERROR)) {
                    if (jsonObject.has(ServerRequest.SMS_VERIFICATION_ERROR)) {
                        int verificationErrorCode = jsonObject.getInt(ServerRequest.SMS_VERIFICATION_ERROR);

                        if (verificationErrorCode == 1) {
                            AlertDialog.Builder pleaseTryLogin = new AlertDialog.Builder(RegisterActivity.this);
                            pleaseTryLogin.setMessage(jsonObject.getString("message"));
                            pleaseTryLogin.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    startLoginActivityAutoStart(RegisterActivity.this);
                                }
                            });
                            pleaseTryLogin.show();
                        }
                    } else {
                        Toast.makeText(RegisterActivity.this, jsonObject.getString("message"),
                                Toast.LENGTH_SHORT).show();
                    }
                }
            } catch (JSONException ex) {
                ex.printStackTrace();
                throw new RuntimeException("Server response cannot be cast to JSONObject");
            }
        }

        @Override
        public void error(int errorCode) {
            Toast.makeText(RegisterActivity.this,
                    " ?!   ?  !",
                    Toast.LENGTH_SHORT).show();
        }
    });
    queryMaster.start();
}

From source file:project.cs.lisa.netinf.node.resolution.NameResolutionService.java

/**
 * Creates an HTTP POST representation of a NetInf PUBLISH message.
 * @param io// w w w  . j  av a  2 s .co m
 *     The information object to publish
 * @return
 *     A HttpPost representing the NetInf PUBLISH message
 * @throws UnsupportedEncodingException
 *     In case the encoding is not supported
 */
private HttpPost createPublish(InformationObject io) throws UnsupportedEncodingException {

    Log.d(TAG, "createPublish()");

    // Extracting values from IO's identifier
    String hashAlg = getHashAlg(io.getIdentifier());
    String hash = getHash(io.getIdentifier());
    String contentType = getContentType(io.getIdentifier());
    String meta = getMetadata(io.getIdentifier());
    String bluetoothMac = getBluetoothMac(io);
    String filePath = getFilePath(io);

    HttpPost post = new HttpPost(mHost + ":" + mPort + "/netinfproto/publish");

    MultipartEntity entity = new MultipartEntity();

    StringBody uri = new StringBody("ni:///" + hashAlg + ";" + hash + "?ct=" + contentType);
    entity.addPart("URI", uri);

    StringBody msgid = new StringBody(Integer.toString(mRandomGenerator.nextInt(MSG_ID_MAX)));
    entity.addPart("msgid", msgid);

    if (bluetoothMac != null) {
        StringBody l = new StringBody(bluetoothMac);
        entity.addPart("loc1", l);
    }

    if (meta != null) {
        StringBody ext = new StringBody(meta.toString());
        entity.addPart("ext", ext);
    }

    if (filePath != null) {
        StringBody fullPut = new StringBody("true");
        entity.addPart("fullPut", fullPut);
        FileBody octets = new FileBody(new File(filePath));
        entity.addPart("octets", octets);
    }

    StringBody rform = new StringBody("json");
    entity.addPart("rform", rform);

    try {
        entity.writeTo(System.out);
    } catch (IOException e) {
        Log.e(TAG, "Failed to write MultipartEntity to System.out");
    }

    post.setEntity(entity);
    return post;
}

From source file:org.n52.oss.ui.controllers.ScriptController.java

@RequestMapping(method = RequestMethod.POST, value = "/upload")
public String processForm(@ModelAttribute(value = "uploadForm") uploadForm form, ModelMap map) {
    String s = form.getFile().getFileItem().getName();
    MultipartEntity multipartEntity = new MultipartEntity();
    UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication()
            .getPrincipal();/*from  w  w  w .  j a  va 2 s. co  m*/
    String token = userDetails.getPassword();

    // upload the file
    File dest = new File(s);
    try {
        System.out.println("Chosen license:" + form.getLicense());
        log.info("Chosen license:" + form.getLicense());
        form.getFile().transferTo(dest);
        UserDetails details = (UserDetails) SecurityContextHolder.getContext().getAuthentication()
                .getPrincipal();
        multipartEntity.addPart("file", new FileBody(dest));
        multipartEntity.addPart("user", new StringBody(details.getUsername()));
        multipartEntity.addPart("licenseCode", new StringBody(form.getLicense()));
        multipartEntity.addPart("auth_token", new StringBody(token));
        HttpPost post = new HttpPost(OSSConstants.BASE_URL + "/OpenSensorSearch/script/submit");
        post.setEntity(multipartEntity);
        org.apache.http.client.HttpClient client = new DefaultHttpClient();
        HttpResponse resp;
        resp = client.execute(post);
        int responseCode = resp.getStatusLine().getStatusCode();
        StringBuilder builder = new StringBuilder();
        String str = null;
        BufferedReader reader = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
        while ((str = reader.readLine()) != null)
            builder.append(str);
        System.out.println("return  id:" + builder.toString());
        log.info("return id:" + builder.toString());

        if (responseCode == 200) {
            map.addAttribute("harvestSuccess", true);
            map.addAttribute("resultScript", builder.toString());
            map.addAttribute("license", form.getLicense());
            return "script/status";
        } else {
            map.addAttribute("harvestError", true);
            return "script/status";
        }
    } catch (Exception e) {
        map.addAttribute("errorMSG", e);
        return "script/status?fail";
    }
}