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.versacomllc.audit.network.sync.SyncAdapter.java

private String uploadFile(String path) {

    String downloadPath = Constants.FILE_CONTENT_PATH;

    if (TextUtils.isEmpty(path)) {
        Log.d(LOG_TAG, "File path is empty.");
        return null;
    }//from   w  ww .  j  av a 2  s  .  com

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

        HttpPost httppost = new HttpPost(FILE_UPLOAD_PATH);
        String mimeType = URLConnection.guessContentTypeFromName(path);
        FileBody bin = new FileBody(file, mimeType);

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart(file.getName(), bin);

        httppost.setEntity(reqEntity);

        Log.i(TAG, "executing request " + httppost.getRequestLine());
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();

        if (resEntity != null) {
            Log.i(TAG, "Response content length: " + resEntity.getContentLength());
        }
        downloadPath = downloadPath + file.getName();

    } catch (ClientProtocolException e) {

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

        e.printStackTrace();
    } finally {
        try {
            httpclient.getConnectionManager().shutdown();
        } catch (Exception ignore) {
        }
    }
    return downloadPath;
}

From source file:com.ginstr.android.service.opencellid.upload.data.MeasurementsUploaderService.java

/**
 * Used to upload entries from networks table to OCID servers.
 */// w  ww . j  a va2s .c  om
private void uploadNetworks() {
    writeToLog("uploadNetworks()");

    String existingFileName = "uploadNetworks.csv";
    String data = null;

    NetworkDBIterator dbIterator = mDatabase.getNonUploadedNetworks();
    try {
        if (dbIterator.getCount() > 0) {
            //timestamp, mcc, mnc, net (network type), nen (network name)
            StringBuilder sb = new StringBuilder("timestamp,mcc,mnc,net,nen" + ((char) 0xA));

            while (dbIterator.hasNext() && uploadThreadRunning) {
                Network network = dbIterator.next();
                sb.append(network.getTimestamp()).append(",");
                sb.append(network.getMcc()).append(",");
                sb.append(network.getMnc()).append(",");
                sb.append(network.getType()).append(",");
                sb.append(network.getName());
                sb.append(((char) 0xA));
            }

            data = sb.toString();

        } else {
            writeToLog("No networks for upload.");
            return;
        }
    } finally {
        dbIterator.close();
    }

    writeToLog("uploadNetworks(): " + data);

    if (uploadThreadRunning) {

        try {
            httppost = new HttpPost(networksUrl);

            HttpResponse response = null;

            writeToLog("Upload request URL: " + httppost.getURI());

            if (uploadThreadRunning) {
                MultipartEntity mpEntity = new MultipartEntity();
                mpEntity.addPart("apikey", new StringBody(apiKey));
                mpEntity.addPart("datafile", new InputStreamBody(new ByteArrayInputStream(data.getBytes()),
                        "text/csv", existingFileName));

                ByteArrayOutputStream bArrOS = new ByteArrayOutputStream();
                // reqEntity is the MultipartEntity instance
                mpEntity.writeTo(bArrOS);
                bArrOS.flush();
                ByteArrayEntity bArrEntity = new ByteArrayEntity(bArrOS.toByteArray());
                bArrOS.close();

                bArrEntity.setChunked(false);
                bArrEntity.setContentEncoding(mpEntity.getContentEncoding());
                bArrEntity.setContentType(mpEntity.getContentType());

                httppost.setEntity(bArrEntity);

                response = httpclient.execute(httppost);
                if (response == null) {
                    writeToLog("Upload: null HTTP-response");
                    throw new IllegalStateException("no HTTP-response from server");
                }

                HttpEntity resEntity = response.getEntity();

                writeToLog("Response: " + response.getStatusLine().getStatusCode() + " - "
                        + response.getStatusLine());

                if (resEntity != null) {
                    writeToLog("Response content: " + EntityUtils.toString(resEntity));
                    resEntity.consumeContent();
                }
            }

            if (uploadThreadRunning) {
                if (response == null) {
                    writeToLog(": " + "null response");

                    throw new IllegalStateException("no response");
                }
                if (response.getStatusLine() == null) {
                    writeToLog(": " + "null HTTP-status-line");

                    throw new IllegalStateException("no HTTP-status returned");
                }
                if (response.getStatusLine().getStatusCode() == 200) {
                    mDatabase.setAllNetworksUploaded();
                } else if (response.getStatusLine().getStatusCode() != 200) {
                    throw new IllegalStateException(
                            response.getStatusLine().getStatusCode() + " HTTP-status returned");
                }
            }

        } catch (Exception e) {
            // httppost cancellation throws exceptions
            if (uploadThreadRunning) {
                writeExceptionToLog(e);
            }
        }
    }
}

From source file:net.fluidnexus.FluidNexusAndroid.services.NexusServiceThread.java

/**
 * Start the listeners for zeroconf services
 *//*from   www.j  a va  2s  . co m*/
public void doStateNone() {
    if (wifiManager.getWifiState() == wifiManager.WIFI_STATE_ENABLED) {
        Cursor c = messagesProviderHelper.publicMessages();

        while (c.isAfterLast() == false) {
            String message_hash = c.getString(c.getColumnIndex(MessagesProviderHelper.KEY_MESSAGE_HASH));
            boolean result = checkHash(message_hash);

            if (!result) {
                try {
                    JSONObject message = new JSONObject();
                    message.put("message_title",
                            c.getString(c.getColumnIndex(MessagesProviderHelper.KEY_TITLE)));
                    message.put("message_content",
                            c.getString(c.getColumnIndex(MessagesProviderHelper.KEY_CONTENT)));
                    message.put("message_hash",
                            c.getString(c.getColumnIndex(MessagesProviderHelper.KEY_MESSAGE_HASH)));
                    message.put("message_type", c.getInt(c.getColumnIndex(MessagesProviderHelper.KEY_TYPE)));
                    message.put("message_time", c.getFloat(c.getColumnIndex(MessagesProviderHelper.KEY_TIME)));
                    message.put("message_received_time",
                            c.getFloat(c.getColumnIndex(MessagesProviderHelper.KEY_RECEIVED_TIME)));
                    message.put("message_priority",
                            c.getInt(c.getColumnIndex(MessagesProviderHelper.KEY_PRIORITY)));

                    String attachment_path = c
                            .getString(c.getColumnIndex(MessagesProviderHelper.KEY_ATTACHMENT_PATH));

                    //String serializedMessage = message.toString();

                    // First, get our nonce
                    consumer = new CommonsHttpOAuthConsumer(key, secret);
                    consumer.setTokenWithSecret(token, token_secret);
                    HttpPost nonce_request = new HttpPost(NEXUS_NONCE_URL);
                    consumer.sign(nonce_request);
                    HttpClient client = new DefaultHttpClient();
                    String response = client.execute(nonce_request, new BasicResponseHandler());
                    JSONObject object = new JSONObject(response);
                    String nonce = object.getString("nonce");

                    // Then, take our nonce and key and put them in the message
                    message.put("message_nonce", nonce);
                    message.put("message_key", key);

                    // Setup our multipart entity
                    MultipartEntity entity = new MultipartEntity();

                    // Deal with file attachment
                    if (!attachment_path.equals("")) {
                        File file = new File(attachment_path);
                        ContentBody cbFile = new FileBody(file);
                        entity.addPart("message_attachment", cbFile);

                        // add the original filename to the message
                        message.put("message_attachment_original_filename", c.getString(
                                c.getColumnIndex(MessagesProviderHelper.KEY_ATTACHMENT_ORIGINAL_FILENAME)));
                    }

                    String serializedMessage = message.toString();
                    ContentBody messageBody = new StringBody(serializedMessage);
                    entity.addPart("message", messageBody);

                    HttpPost message_request = new HttpPost(NEXUS_MESSAGE_URL);
                    message_request.setEntity(entity);

                    client = new DefaultHttpClient();
                    client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

                    response = client.execute(message_request, new BasicResponseHandler());
                    object = new JSONObject(response);
                    boolean message_result = object.getBoolean("result");

                    if (message_result) {
                        ContentValues values = new ContentValues();
                        values.put(MessagesProviderHelper.KEY_MESSAGE_HASH, message_hash);
                        values.put(MessagesProviderHelper.KEY_UPLOADED, 1);
                        int res = messagesProviderHelper
                                .setPublic(c.getLong(c.getColumnIndex(MessagesProviderHelper.KEY_ID)), values);
                        if (res == 0) {
                            log.debug("Message with hash " + message_hash
                                    + " not found; this should never happen!");
                        }
                    }

                } catch (OAuthMessageSignerException e) {
                    log.debug("OAuthMessageSignerException: " + e);
                } catch (OAuthExpectationFailedException e) {
                    log.debug("OAuthExpectationFailedException: " + e);
                } catch (OAuthCommunicationException e) {
                    log.debug("OAuthCommunicationException: " + e);
                } catch (JSONException e) {
                    log.debug("JSON Error: " + e);
                } catch (IOException e) {
                    log.debug("IOException: " + e);
                }
            }
            c.moveToNext();
        }

        c.close();

    }

    setServiceState(STATE_SERVICE_WAIT);
}

From source file:org.deviceconnect.android.profile.restful.test.StressTestCase.java

private HttpUriRequest createFileSendRequest() throws IOException {
    final String name = "test.png";
    URIBuilder builder = TestURIBuilder.createURIBuilder();
    builder.setProfile(FileProfileConstants.PROFILE_NAME);
    builder.setAttribute(FileProfileConstants.ATTRIBUTE_SEND);
    builder.addParameter(DConnectProfileConstants.PARAM_DEVICE_ID, getDeviceId());
    builder.addParameter(DConnectMessage.EXTRA_ACCESS_TOKEN, getAccessToken());
    builder.addParameter(FileProfileConstants.PARAM_PATH, "/test/test.png");

    AssetManager manager = getApplicationContext().getAssets();
    InputStream in = null;//  w  w  w  .  ja  v a 2  s.c om
    try {
        MultipartEntity entity = new MultipartEntity();
        in = manager.open(name);
        // ??
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int len;
        byte[] buf = new byte[BUF_SIZE];
        while ((len = in.read(buf)) > 0) {
            baos.write(buf, 0, len);
        }
        // ?
        entity.addPart(FileProfileConstants.PARAM_DATA, new BinaryBody(baos.toByteArray(), name));

        HttpPost request = new HttpPost(builder.toString());
        request.setEntity(entity);
        return request;
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:org.nema.medical.mint.dcm2mint.ProcessImportDir.java

private JobInfo send(final File metadataFile, final BinaryData binaryData, final Collection<File> studyFiles,
        final StudyQueryInfo studyQueryInfo) throws IOException, SAXException {
    final HttpPost httpPost = new HttpPost(studyQueryInfo == null ? createURI : updateURI);
    final MultipartEntity entity = new MultipartEntity();

    if (studyQueryInfo != null) {
        entity.addPart(HttpMessagePart.STUDY_UUID.toString(), new StringBody(studyQueryInfo.studyUUID));
    }/*from w  w  w  .j  a  v  a  2s .  co  m*/

    final StudyMetadata study = useXMLNotGPB ? StudyIO.parseFromXML(metadataFile)
            : StudyIO.parseFromGPB(metadataFile);
    if (studyQueryInfo != null) {
        //Specify current study version
        entity.addPart(HttpMessagePart.OLD_VERSION.toString(), new StringBody(studyQueryInfo.studyVersion));
    }

    //Pretty significant in-memory operations, so scoping to get references released ASAP
    {
        final byte[] metaInBuffer;
        {
            final ByteArrayOutputStream metaOut = new ByteArrayOutputStream(10000);
            if (useXMLNotGPB) {
                StudyIO.writeToXML(study, metaOut);
            } else {
                StudyIO.writeToGPB(study, metaOut);
            }
            metaInBuffer = metaOut.toByteArray();
        }
        final ByteArrayInputStream metaIn = new ByteArrayInputStream(metaInBuffer);
        //We must distinguish MIME types for GPB vs. XML so that the server can handle them properly
        entity.addPart(metadataFile.getName(), new InputStreamBody(metaIn,
                useXMLNotGPB ? "text/xml" : "application/octet-stream", metadataFile.getName()));
    }

    //We support only one type
    assert binaryData instanceof BinaryDcmData;
    {
        int i = 0;
        for (final InputStream binaryStream : iter(((BinaryDcmData) binaryData).streamIterator())) {
            final String fileName = "binary" + i++;
            entity.addPart(fileName, new InputStreamBody(binaryStream, fileName));
        }
    }

    //Debugging only
    //        int i = 0;
    //        for (final InputStream binaryStream: Iter.iter(((BinaryDcmData) binaryData).streamIterator())) {
    //            final OutputStream testout = new BufferedOutputStream(new FileOutputStream("E:/testdata/" + i), 10000);
    //            for(;;) {
    //                final int val = binaryStream.read();
    //                if (val == -1) {
    //                    break;
    //                }
    //                testout.write(val);
    //            }
    //            testout.close();
    //            ++i;
    //        }

    httpPost.setEntity(entity);

    final String response = httpClient.execute(httpPost, new BasicResponseHandler());
    final long uploadEndTime = System.currentTimeMillis();

    LOG.debug("Server response:" + response);

    final String jobID;
    final String studyID;
    final Document responseDoc = documentBuilder.parse(new ByteArrayInputStream(response.getBytes()));
    try {
        jobID = xPath.evaluate("/jobStatus/@jobID", responseDoc).trim();
        studyID = xPath.evaluate("/jobStatus/@studyUUID", responseDoc).trim();
    } catch (final XPathExpressionException e) {
        //This shouldn't happen
        throw new RuntimeException(e);
    }
    final JobInfo jobInfo = new JobInfo(jobID, studyID, studyFiles, uploadEndTime);
    jobIDInfo.put(jobID, jobInfo);
    return jobInfo;
}

From source file:com.francisli.processing.http.HttpClient.java

/**
 * @param files HashMap: a collection of files to send to the server
 *//*  w w w . ja  v a  2  s  .  co  m*/
public HttpRequest POST(String path, Map params, Map files) {
    //// clean up path a little bit- remove whitespace, add slash prefix
    path = path.trim();
    if (!path.startsWith("/")) {
        path = "/" + path;
    }
    //// finally, invoke request
    HttpPost post = new HttpPost(getHost().toURI() + path);
    MultipartEntity multipart = null;
    //// if files passed, set up a multipart request
    if (files != null) {
        multipart = new MultipartEntity();
        post.setEntity(multipart);
        for (Object key : files.keySet()) {
            Object value = files.get(key);
            if (value instanceof byte[]) {
                multipart.addPart((String) key, new ByteArrayBody((byte[]) value, "bytes.dat"));
            } else if (value instanceof String) {
                File file = new File((String) value);
                if (!file.exists()) {
                    file = parent.sketchFile((String) value);
                }
                multipart.addPart((String) key, new FileBody(file));
            }
        }
    }
    //// if params passed, format into a query string and append
    if (params != null) {
        if (multipart == null) {
            ArrayList<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
            for (Object key : params.keySet()) {
                Object value = params.get(key);
                pairs.add(new BasicNameValuePair(key.toString(), value.toString()));
            }
            String queryString = URLEncodedUtils.format(pairs, HTTP.UTF_8);
            if (path.contains("?")) {
                path = path + "&" + queryString;
            } else {
                path = path + "?" + queryString;
            }
            try {
                post.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));
            } catch (UnsupportedEncodingException ex) {
                System.err.println("HttpClient: Unable to set POST data from parameters");
            }
        } else {
            for (Object key : params.keySet()) {
                Object value = params.get(key);
                try {
                    multipart.addPart((String) key, new StringBody((String) value));
                } catch (UnsupportedEncodingException ex) {
                    System.err.println("HttpClient: Unable to add " + key + ", " + value);
                }
            }
        }
    }
    if (useOAuth) {
        OAuthConsumer consumer = new CommonsHttpOAuthConsumer(oauthConsumerKey, oauthConsumerSecret);
        consumer.setTokenWithSecret(oauthAccessToken, oauthAccessTokenSecret);
        try {
            consumer.sign(post);
        } catch (Exception e) {
            System.err.println("HttpClient: Unable to sign POST request for OAuth");
        }
    }
    HttpRequest request = new HttpRequest(this, getHost(), post);
    request.start();
    return request;
}

From source file:net.rcarz.jiraclient.RestClient.java

private JSON request(HttpEntityEnclosingRequestBase req, Issue.NewAttachment... attachments)
        throws RestException, IOException {
    if (attachments != null) {
        req.setHeader("X-Atlassian-Token", "nocheck");
        MultipartEntity ent = new MultipartEntity();
        for (Issue.NewAttachment attachment : attachments) {
            String filename = attachment.getFilename();
            Object content = attachment.getContent();
            if (content instanceof byte[]) {
                ent.addPart("file", new ByteArrayBody((byte[]) content, filename));
            } else if (content instanceof InputStream) {
                ent.addPart("file", new InputStreamBody((InputStream) content, filename));
            } else if (content instanceof File) {
                ent.addPart("file", new FileBody((File) content, filename));
            } else if (content == null) {
                throw new IllegalArgumentException("Missing content for the file " + filename);
            } else {
                throw new IllegalArgumentException(
                        "Expected file type byte[], java.io.InputStream or java.io.File but provided "
                                + content.getClass().getName() + " for the file " + filename);
            }/*w  w  w  . ja va  2s.c  o m*/
        }
        req.setEntity(ent);
    }
    return request(req);
}

From source file:net.dahanne.gallery.g2.java.client.business.G2Client.java

private MultipartEntity createMultiPartEntityForSendImageToGallery(int albumName, File imageFile,
        String imageName, String summary, String description) throws GalleryConnectionException {
    if (imageName == null) {
        imageName = imageFile.getName().substring(0, imageFile.getName().indexOf("."));
    }//from  ww  w .j  av a2 s  .c  o m

    MultipartEntity multiPartEntity;
    try {
        multiPartEntity = new MultipartEntity();
        multiPartEntity.addPart("g2_controller", new StringBody("remote.GalleryRemote", UTF_8));
        multiPartEntity.addPart("g2_form[cmd]", new StringBody("add-item", UTF_8));
        multiPartEntity.addPart("g2_form[set_albumName]", new StringBody("" + albumName, UTF_8));
        if (authToken != null) {
            multiPartEntity.addPart("g2_authToken", new StringBody(authToken, UTF_8));
        }
        multiPartEntity.addPart("g2_form[caption]", new StringBody(imageName, UTF_8));
        multiPartEntity.addPart("g2_form[extrafield.Summary]", new StringBody(summary, UTF_8));
        multiPartEntity.addPart("g2_form[extrafield.Description]", new StringBody(description, UTF_8));
        multiPartEntity.addPart("g2_userfile", new FileBody(imageFile));
    } catch (Exception e) {
        throw new GalleryConnectionException(e.getMessage());
    }
    return multiPartEntity;
}

From source file:com.klinker.android.twitter.utils.api_helper.TwitterMultipleImageHelper.java

public String getMediaIds(File[] pics, Twitter twitter) {
    JSONObject jsonresponse = new JSONObject();
    String ids = "";

    for (int i = 0; i < pics.length; i++) {
        File file = pics[i];//from w  w w  .  j  a  va2s .  c o m
        try {
            AccessToken token = twitter.getOAuthAccessToken();
            String oauth_token = token.getToken();
            String oauth_token_secret = token.getTokenSecret();

            // generate authorization header
            String get_or_post = "POST";
            String oauth_signature_method = "HMAC-SHA1";

            String uuid_string = UUID.randomUUID().toString();
            uuid_string = uuid_string.replaceAll("-", "");
            String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here

            // get the timestamp
            Calendar tempcal = Calendar.getInstance();
            long ts = tempcal.getTimeInMillis();// get current time in milliseconds
            String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds

            // the parameter string must be in alphabetical order, "text" parameter added at end
            String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce="
                    + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp="
                    + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0";
            System.out.println("Twitter.updateStatusWithMedia(): parameter_string=" + parameter_string);

            String twitter_endpoint = "https://upload.twitter.com/1.1/media/upload.json";
            String twitter_endpoint_host = "upload.twitter.com";
            String twitter_endpoint_path = "/1.1/media/upload.json";
            String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&"
                    + encode(parameter_string);
            String oauth_signature = computeSignature(signature_base_string,
                    AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret));

            String authorization_header_string = "OAuth oauth_consumer_key=\""
                    + AppSettings.TWITTER_CONSUMER_KEY
                    + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp
                    + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\""
                    + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\"";

            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, "UTF-8");
            HttpProtocolParams.setUserAgent(params, "HttpCore/1.1");
            HttpProtocolParams.setUseExpectContinue(params, false);
            HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
                    // Required protocol interceptors
                    new RequestContent(), new RequestTargetHost(),
                    // Recommended protocol interceptors
                    new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

            HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
            HttpContext context = new BasicHttpContext(null);
            HttpHost host = new HttpHost(twitter_endpoint_host, 443);
            DefaultHttpClientConnection conn = new DefaultHttpClientConnection();

            context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
            context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

            try {
                try {
                    SSLContext sslcontext = SSLContext.getInstance("TLS");
                    sslcontext.init(null, null, null);
                    SSLSocketFactory ssf = sslcontext.getSocketFactory();
                    Socket socket = ssf.createSocket();
                    socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0);
                    conn.bind(socket, params);

                    BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("POST",
                            twitter_endpoint_path);

                    // need to add status parameter to this POST
                    MultipartEntity reqEntity = new MultipartEntity();

                    FileBody sb_image = new FileBody(file);
                    reqEntity.addPart("media", sb_image);

                    request2.setEntity(reqEntity);
                    request2.setParams(params);

                    request2.addHeader("Authorization", authorization_header_string);
                    System.out.println(
                            "Twitter.updateStatusWithMedia(): Entity, params and header added to request. Preprocessing and executing...");
                    httpexecutor.preProcess(request2, httpproc, context);
                    HttpResponse response2 = httpexecutor.execute(request2, conn, context);
                    System.out.println("Twitter.updateStatusWithMedia(): ... done. Postprocessing...");
                    response2.setParams(params);
                    httpexecutor.postProcess(response2, httpproc, context);
                    String responseBody = EntityUtils.toString(response2.getEntity());
                    System.out.println("Twitter.updateStatusWithMedia(): done. response=" + responseBody);
                    // error checking here. Otherwise, status should be updated.
                    jsonresponse = new JSONObject(responseBody);
                    if (jsonresponse.has("errors")) {
                        JSONObject temp_jo = new JSONObject();
                        temp_jo.put("response_status", "error");
                        temp_jo.put("message",
                                jsonresponse.getJSONArray("errors").getJSONObject(0).getString("message"));
                        temp_jo.put("twitter_code",
                                jsonresponse.getJSONArray("errors").getJSONObject(0).getInt("code"));
                        jsonresponse = temp_jo;
                    }

                    // add it to the media_ids string
                    ids += jsonresponse.getString("media_id_string");
                    if (i != pics.length - 1) {
                        ids += ",";
                    }

                    conn.close();
                } catch (HttpException he) {
                    System.out.println(he.getMessage());
                    jsonresponse.put("response_status", "error");
                    jsonresponse.put("message",
                            "updateStatusWithMedia HttpException message=" + he.getMessage());
                    return null;
                } catch (NoSuchAlgorithmException nsae) {
                    System.out.println(nsae.getMessage());
                    jsonresponse.put("response_status", "error");
                    jsonresponse.put("message",
                            "updateStatusWithMedia NoSuchAlgorithmException message=" + nsae.getMessage());
                    return null;
                } catch (KeyManagementException kme) {
                    System.out.println(kme.getMessage());
                    jsonresponse.put("response_status", "error");
                    jsonresponse.put("message",
                            "updateStatusWithMedia KeyManagementException message=" + kme.getMessage());
                    return null;
                } finally {
                    conn.close();
                }
            } catch (IOException ioe) {
                ioe.printStackTrace();
                jsonresponse.put("response_status", "error");
                jsonresponse.put("message", "updateStatusWithMedia IOException message=" + ioe.getMessage());
                return null;
            }
        } catch (Exception e) {
            return null;
        }

    }
    return ids;
}

From source file:org.deviceconnect.android.profile.restful.test.NormalFileProfileTestCase.java

/**
 * ???.//w w  w  . ja va  2  s .  c  o  m
 * <pre>
 * Method: POST
 * Path: /file/send?deviceid=xxxx&filename=xxxx
 * </pre>
 * <pre>
 * ??
 * result?0???????
 * </pre>
 */
public void testSend() {
    final String name = "test.png";
    URIBuilder builder = TestURIBuilder.createURIBuilder();
    builder.setProfile(FileProfileConstants.PROFILE_NAME);
    builder.setAttribute(FileProfileConstants.ATTRIBUTE_SEND);
    builder.addParameter(DConnectProfileConstants.PARAM_DEVICE_ID, getDeviceId());
    builder.addParameter(DConnectMessage.EXTRA_ACCESS_TOKEN, getAccessToken());
    builder.addParameter(FileProfileConstants.PARAM_PATH, "/test/test.png");
    builder.addParameter(FileProfileConstants.PARAM_FILE_TYPE,
            String.valueOf(FileProfileConstants.FileType.FILE.getValue()));

    AssetManager manager = getApplicationContext().getAssets();
    InputStream in = null;
    try {
        MultipartEntity entity = new MultipartEntity();
        in = manager.open(name);
        // ??
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        int len;
        byte[] buf = new byte[BUF_SIZE];
        while ((len = in.read(buf)) > 0) {
            baos.write(buf, 0, len);
        }
        // ?
        entity.addPart(FileProfileConstants.PARAM_DATA, new BinaryBody(baos.toByteArray(), name));

        HttpPost request = new HttpPost(builder.toString());
        request.setEntity(entity);

        JSONObject root = sendRequest(request);
        assertResultOK(root);
    } catch (JSONException e) {
        fail("Exception in JSONObject." + e.getMessage());
    } catch (IOException e) {
        fail("IOException in JSONObject." + e.getMessage());
    } finally {
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
            }
        }
    }
}