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

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

Introduction

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

Prototype

public FileBody(final File file) 

Source Link

Usage

From source file:com.qmetry.qaf.automation.integration.qmetry.qmetry7.QMetryRestWebservice.java

public int attachTestLogs(long tcVersionIdASEntityId, File filePath) {
    try {/*w ww. j av a  2  s. com*/
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd-HHmmss");

        final String CurrentDate = format.format(new Date());
        Path path = Paths.get(filePath.toURI());
        byte[] outFileArray = Files.readAllBytes(path);

        if (outFileArray != null) {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            try {
                HttpPost httppost = new HttpPost(serviceUrl + "/rest/attachments");

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

                FileBody bin = new FileBody(filePath);
                builder.addPart("file", bin);

                HttpEntity reqEntity = builder.build();
                httppost.setEntity(reqEntity);
                httppost.addHeader("usertoken", token);
                httppost.addHeader("scope", scope);

                CloseableHttpResponse response = httpclient.execute(httppost);
                String str = null;
                try {
                    str = EntityUtils.toString(response.getEntity());
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                }
                JsonElement gson = new Gson().fromJson(str, JsonElement.class);
                JsonElement data = gson.getAsJsonObject().get("data");
                int id = Integer.parseInt(data.getAsJsonArray().get(0).getAsJsonObject().get("id").toString());
                return id;
            } finally {
                httpclient.close();
            }
        } else {
            System.out.println(filePath + " file does not exists");
        }
    } catch (Exception ex) {
        System.out.println("Error in attaching file - " + filePath);
        System.out.println(ex.getMessage());
    }
    return 0;
}

From source file:org.fcrepo.test.api.TestAdminAPI.java

private HttpResponse putOrPost(String method, Object requestContent, boolean authenticate) throws Exception {

    if (url == null || url.length() == 0) {
        throw new IllegalArgumentException("url must be a non-empty value");
    } else if (!(url.startsWith("http://") || url.startsWith("https://"))) {
        url = getBaseURL() + url;/*from   w  ww .j av  a2  s  . c  om*/
    }

    HttpEntityEnclosingRequestBase httpMethod = null;
    try {
        if (method.equals("PUT")) {
            httpMethod = new HttpPut(url);
        } else if (method.equals("POST")) {
            httpMethod = new HttpPost(url);
        } else {
            throw new IllegalArgumentException("method must be one of PUT or POST.");
        }
        httpMethod.setHeader(HttpHeaders.CONNECTION, "Keep-Alive");
        if (requestContent != null) {
            if (requestContent instanceof String) {
                StringEntity entity = new StringEntity((String) requestContent, Charset.forName("UTF-8"));
                entity.setChunked(chunked);
                httpMethod.setEntity(entity);
            } else if (requestContent instanceof File) {
                MultipartEntity entity = new MultipartEntity();
                entity.addPart(((File) requestContent).getName(), new FileBody((File) requestContent));
                entity.addPart("param_name", new StringBody("value"));
                httpMethod.setEntity(entity);
            } else {
                throw new IllegalArgumentException("requestContent must be a String or File");
            }
        }
        return getClient(authenticate).execute(httpMethod);
    } finally {
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }
}

From source file:com.ibuildapp.romanblack.FanWallPlugin.data.Statics.java

public static FanWallMessage postMessage(String msg, String imagePath, int parentId, int replyId,
        boolean withGps) {
    HttpParams params = new BasicHttpParams();
    params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpClient httpClient = new DefaultHttpClient(params);

    try {//from   www.  j a va  2  s.c om
        HttpPost httpPost = new HttpPost(Statics.BASE_URL + "/");

        MultipartEntity multipartEntity = new MultipartEntity();
        multipartEntity.addPart("app_id",
                new StringBody(com.appbuilder.sdk.android.Statics.appId, Charset.forName("UTF-8")));
        multipartEntity.addPart("token",
                new StringBody(com.appbuilder.sdk.android.Statics.appToken, Charset.forName("UTF-8")));
        multipartEntity.addPart("module_id", new StringBody(Statics.MODULE_ID, Charset.forName("UTF-8")));

        // ? ?
        multipartEntity.addPart("parent_id",
                new StringBody(Integer.toString(parentId), Charset.forName("UTF-8")));
        multipartEntity.addPart("reply_id",
                new StringBody(Integer.toString(replyId), Charset.forName("UTF-8")));

        if (Authorization.getAuthorizedUser().getAccountType() == User.ACCOUNT_TYPES.FACEBOOK) {
            multipartEntity.addPart("account_type", new StringBody("facebook", Charset.forName("UTF-8")));
        } else if (Authorization.getAuthorizedUser().getAccountType() == User.ACCOUNT_TYPES.TWITTER) {
            multipartEntity.addPart("account_type", new StringBody("twitter", Charset.forName("UTF-8")));
        } else {
            multipartEntity.addPart("account_type", new StringBody("ibuildapp", Charset.forName("UTF-8")));
        }
        multipartEntity.addPart("account_id",
                new StringBody(Authorization.getAuthorizedUser().getAccountId(), Charset.forName("UTF-8")));
        multipartEntity.addPart("user_name",
                new StringBody(Authorization.getAuthorizedUser().getUserName(), Charset.forName("UTF-8")));
        multipartEntity.addPart("user_avatar",
                new StringBody(Authorization.getAuthorizedUser().getAvatarUrl(), Charset.forName("UTF-8")));

        if (withGps) {
            if (Statics.currentLocation != null) {
                multipartEntity.addPart("latitude",
                        new StringBody(Statics.currentLocation.getLatitude() + "", Charset.forName("UTF-8")));
                multipartEntity.addPart("longitude",
                        new StringBody(Statics.currentLocation.getLongitude() + "", Charset.forName("UTF-8")));
            }
        }

        multipartEntity.addPart("text", new StringBody(msg, Charset.forName("UTF-8")));

        if (!TextUtils.isEmpty(imagePath)) {
            multipartEntity.addPart("images", new FileBody(new File(imagePath)));
        }

        httpPost.setEntity(multipartEntity);

        String resp = httpClient.execute(httpPost, new BasicResponseHandler());

        return JSONParser.parseMessagesString(resp).get(0);

    } catch (Exception e) {
        return null;
    }
}

From source file:org.eweb4j.spiderman.plugin.util.PageFetcherImpl.java

/**
 * /*from   w ww  . j  a  v a2 s.c  o  m*/
 * @date 2013-1-7 ?11:08:54
 * @param toFetchURL
 * @return
 */
public FetchResult request(FetchRequest req) throws Exception {
    FetchResult fetchResult = new FetchResult();
    HttpUriRequest request = null;
    HttpEntity entity = null;
    String toFetchURL = req.getUrl();
    boolean isPost = false;
    try {
        if (Http.Method.GET.equalsIgnoreCase(req.getHttpMethod()))
            request = new HttpGet(toFetchURL);
        else if (Http.Method.POST.equalsIgnoreCase(req.getHttpMethod())) {
            request = new HttpPost(toFetchURL);
            isPost = true;
        } else if (Http.Method.PUT.equalsIgnoreCase(req.getHttpMethod()))
            request = new HttpPut(toFetchURL);
        else if (Http.Method.HEAD.equalsIgnoreCase(req.getHttpMethod()))
            request = new HttpHead(toFetchURL);
        else if (Http.Method.OPTIONS.equalsIgnoreCase(req.getHttpMethod()))
            request = new HttpOptions(toFetchURL);
        else if (Http.Method.DELETE.equalsIgnoreCase(req.getHttpMethod()))
            request = new HttpDelete(toFetchURL);
        else
            throw new Exception("Unknown http method name");

        //???,??
        // TODO ?delay?
        synchronized (mutex) {
            //??
            long now = (new Date()).getTime();
            //?Host??
            if (now - lastFetchTime < config.getPolitenessDelay())
                Thread.sleep(config.getPolitenessDelay() - (now - lastFetchTime));
            //????HOST??URL
            lastFetchTime = (new Date()).getTime();
        }

        //GZIP???GZIP?
        request.addHeader("Accept-Encoding", "gzip");
        for (Iterator<Entry<String, String>> it = headers.entrySet().iterator(); it.hasNext();) {
            Entry<String, String> entry = it.next();
            request.addHeader(entry.getKey(), entry.getValue());
        }

        //?
        Header[] headers = request.getAllHeaders();
        for (Header h : headers) {
            Map<String, List<String>> hs = req.getHeaders();
            String key = h.getName();
            List<String> val = hs.get(key);
            if (val == null)
                val = new ArrayList<String>();
            val.add(h.getValue());

            hs.put(key, val);
        }
        req.getCookies().putAll(this.cookies);
        fetchResult.setReq(req);

        HttpEntity reqEntity = null;
        if (Http.Method.POST.equalsIgnoreCase(req.getHttpMethod())
                || Http.Method.PUT.equalsIgnoreCase(req.getHttpMethod())) {
            if (!req.getFiles().isEmpty()) {
                reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
                for (Iterator<Entry<String, List<File>>> it = req.getFiles().entrySet().iterator(); it
                        .hasNext();) {
                    Entry<String, List<File>> e = it.next();
                    String paramName = e.getKey();
                    for (File file : e.getValue()) {
                        // For File parameters
                        ((MultipartEntity) reqEntity).addPart(paramName, new FileBody(file));
                    }
                }

                for (Iterator<Entry<String, List<Object>>> it = req.getParams().entrySet().iterator(); it
                        .hasNext();) {
                    Entry<String, List<Object>> e = it.next();
                    String paramName = e.getKey();
                    for (Object paramValue : e.getValue()) {
                        // For usual String parameters
                        ((MultipartEntity) reqEntity).addPart(paramName, new StringBody(
                                String.valueOf(paramValue), "text/plain", Charset.forName("UTF-8")));
                    }
                }
            } else {
                List<NameValuePair> params = new ArrayList<NameValuePair>(req.getParams().size());
                for (Iterator<Entry<String, List<Object>>> it = req.getParams().entrySet().iterator(); it
                        .hasNext();) {
                    Entry<String, List<Object>> e = it.next();
                    String paramName = e.getKey();
                    for (Object paramValue : e.getValue()) {
                        params.add(new BasicNameValuePair(paramName, String.valueOf(paramValue)));
                    }
                }
                reqEntity = new UrlEncodedFormEntity(params, HTTP.UTF_8);
            }

            if (isPost)
                ((HttpPost) request).setEntity(reqEntity);
            else
                ((HttpPut) request).setEntity(reqEntity);
        }

        //??
        HttpResponse response = httpClient.execute(request);
        headers = response.getAllHeaders();
        for (Header h : headers) {
            Map<String, List<String>> hs = fetchResult.getHeaders();
            String key = h.getName();
            List<String> val = hs.get(key);
            if (val == null)
                val = new ArrayList<String>();
            val.add(h.getValue());

            hs.put(key, val);
        }
        //URL
        fetchResult.setFetchedUrl(toFetchURL);
        String uri = request.getURI().toString();
        if (!uri.equals(toFetchURL))
            if (!URLCanonicalizer.getCanonicalURL(uri).equals(toFetchURL))
                fetchResult.setFetchedUrl(uri);

        entity = response.getEntity();
        //???
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            if (statusCode != HttpStatus.SC_NOT_FOUND) {
                Header locationHeader = response.getFirstHeader("Location");
                //301?302?URL??
                if (locationHeader != null && (statusCode == HttpStatus.SC_MOVED_PERMANENTLY
                        || statusCode == HttpStatus.SC_MOVED_TEMPORARILY))
                    fetchResult.setMovedToUrl(
                            URLCanonicalizer.getCanonicalURL(locationHeader.getValue(), toFetchURL));
            }
            //???OKURLstatusCode??
            //???
            if (this.site.getSkipStatusCode() != null && this.site.getSkipStatusCode().trim().length() > 0) {
                String[] scs = this.site.getSkipStatusCode().split(",");
                for (String code : scs) {
                    int c = CommonUtil.toInt(code);
                    //????entity
                    if (statusCode == c) {
                        assemPage(fetchResult, entity);
                        break;
                    }
                }
            }
            fetchResult.setStatusCode(statusCode);
            return fetchResult;
        }

        //??
        if (entity != null) {
            fetchResult.setStatusCode(statusCode);
            assemPage(fetchResult, entity);
            return fetchResult;
        }
    } catch (Throwable e) {
        fetchResult.setFetchedUrl(e.toString());
        fetchResult.setStatusCode(Status.INTERNAL_SERVER_ERROR.ordinal());
        return fetchResult;
    } finally {
        try {
            if (entity == null && request != null)
                request.abort();
        } catch (Exception e) {
            throw e;
        }
    }

    fetchResult.setStatusCode(Status.UNSPECIFIED_ERROR.ordinal());
    return fetchResult;
}

From source file:com.makotosan.vimeodroid.vimeo.Methods.java

public void uploadFile(String endpoint, String ticketId, File file, String filename, ProgressListener listener,
        OnTransferringHandler handler) throws OAuthMessageSignerException, OAuthExpectationFailedException,
        OAuthCommunicationException, ClientProtocolException, IOException {
    // final int chunkSize = 512 * 1024; // 512 kB
    // final long pieces = file.length() / chunkSize;
    int chunkId = 0;

    final HttpPost request = new HttpPost(endpoint);

    // BufferedInputStream stream = new BufferedInputStream(new
    // FileInputStream(file));

    // for (chunkId = 0; chunkId < pieces; chunkId++) {
    // byte[] buffer = new byte[chunkSize];

    // stream.skip(chunkId * chunkSize);

    // stream.read(buffer);

    final MultipartEntity entity = new MultipartEntity();
    entity.addPart("chunk_id", new StringBody(String.valueOf(chunkId)));
    entity.addPart("ticket_id", new StringBody(ticketId));
    request.setEntity(new CountingRequestEntity(entity, listener)); // ,
    // chunkId//  www.j  a va  2s  . co m
    // *
    // chunkSize));
    // ByteArrayInputStream arrayStream = new ByteArrayInputStream(buffer);

    Authentication.signRequest(getConsumerInfo(), request);

    entity.addPart("file_data", new FileBody(file));
    // entity.addPart("file_data", new InputStreamBody(arrayStream,
    // filename));

    final HttpClient client = app.getHttpClient();

    handler.onTransferring(request);
    final HttpResponse response = client.execute(request);
    final HttpEntity responseEntity = response.getEntity();
    if (responseEntity != null) {
        responseEntity.consumeContent();
    }
    // }
}

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 ww .j  ava2 s.c  om*/
        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:nl.sogeti.android.gpstracker.actions.ShareTrack.java

/**
 * POST a (GPX) file to the 0.6 API of the OpenStreetMap.org website publishing 
 * this track to the public.// ww  w.  j  av a2 s  .co m
 * 
 * @param fileUri
 * @param contentType
 */
private void sendToOsm(Uri fileUri, Uri trackUri, String contentType) {
    String username = PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.OSM_USERNAME, "");
    String password = PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.OSM_PASSWORD, "");
    String visibility = PreferenceManager.getDefaultSharedPreferences(this).getString(Constants.OSM_VISIBILITY,
            "trackable");
    File gpxFile = new File(fileUri.getEncodedPath());
    String hostname = getString(R.string.osm_post_host);
    Integer port = new Integer(getString(R.string.osm_post_port));
    HttpHost targetHost = new HttpHost(hostname, port, "http");

    DefaultHttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = null;
    String responseText = "";
    int statusCode = 0;
    Cursor metaData = null;
    String sources = null;
    try {
        metaData = this.getContentResolver().query(Uri.withAppendedPath(trackUri, "metadata"),
                new String[] { MetaData.VALUE }, MetaData.KEY + " = ? ",
                new String[] { Constants.DATASOURCES_KEY }, null);
        if (metaData.moveToFirst()) {
            sources = metaData.getString(0);
        }
        if (sources != null && sources.contains(LoggerMap.GOOGLE_PROVIDER)) {
            throw new IOException("Unable to upload track with materials derived from Google Maps.");
        }

        // The POST to the create node
        HttpPost method = new HttpPost(getString(R.string.osm_post_context));

        // Preemptive basic auth on the first request 
        method.addHeader(
                new BasicScheme().authenticate(new UsernamePasswordCredentials(username, password), method));

        // Build the multipart body with the upload data
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        entity.addPart("file", new FileBody(gpxFile));
        entity.addPart("description", new StringBody(queryForTrackName()));
        entity.addPart("tags", new StringBody(queryForNotes()));
        entity.addPart("visibility", new StringBody(visibility));
        method.setEntity(entity);

        // Execute the POST to OpenStreetMap
        response = httpclient.execute(targetHost, method);

        // Read the response
        statusCode = response.getStatusLine().getStatusCode();
        InputStream stream = response.getEntity().getContent();
        responseText = convertStreamToString(stream);
    } catch (IOException e) {
        Log.e(TAG, "Failed to upload to " + targetHost.getHostName() + "Response: " + responseText, e);
        responseText = getString(R.string.osm_failed) + e.getLocalizedMessage();
        Toast toast = Toast.makeText(this, responseText, Toast.LENGTH_LONG);
        toast.show();
    } catch (AuthenticationException e) {
        Log.e(TAG, "Failed to upload to " + targetHost.getHostName() + "Response: " + responseText, e);
        responseText = getString(R.string.osm_failed) + e.getLocalizedMessage();
        Toast toast = Toast.makeText(this, responseText, Toast.LENGTH_LONG);
        toast.show();
    } finally {
        if (metaData != null) {
            metaData.close();
        }
    }

    if (statusCode == 200) {
        Log.i(TAG, responseText);
        CharSequence text = getString(R.string.osm_success) + responseText;
        Toast toast = Toast.makeText(this, text, Toast.LENGTH_LONG);
        toast.show();
    } else {
        Log.e(TAG, "Failed to upload to error code " + statusCode + " " + responseText);
        CharSequence text = getString(R.string.osm_failed) + responseText;
        Toast toast = Toast.makeText(this, text, Toast.LENGTH_LONG);
        toast.show();
    }
}

From source file:sjizl.com.FileUploadTest.java

private void doFileUpload(String path) {

    String username = "";
    String password = "";
    String foto = "";
    String foto_num = "";
    SharedPreferences sp = getApplicationContext().getSharedPreferences("loginSaved", Context.MODE_PRIVATE);
    username = sp.getString("username", null);
    password = sp.getString("password", null);
    foto = sp.getString("foto", null);
    foto_num = sp.getString("foto_num", null);

    File file1 = new File(path);

    String urlString = "http://sjizl.com/postBD/UploadToServer.php?username=" + username + "&password="
            + password;//from   w ww .  j  a va  2 s . c  o  m
    try {
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(urlString);
        FileBody bin1 = new FileBody(file1);

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("uploadedfile1", bin1);

        reqEntity.addPart("user", new StringBody("User"));
        post.setEntity(reqEntity);
        HttpResponse response = client.execute(post);
        resEntity = response.getEntity();
        final String response_str = EntityUtils.toString(resEntity);
        if (resEntity != null) {
            Log.i("RESPONSE", response_str);
            runOnUiThread(new Runnable() {
                public void run() {
                    try {
                        // res.setTextColor(Color.GREEN);
                        // res.setText("n Response from server : n " + response_str);

                        CommonUtilities.custom_toast(getApplicationContext(), FileUploadTest.this,
                                "Upload Complete! ", null, R.drawable.iconbd);

                        Brows();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    } catch (Exception ex) {
        Log.e("Debug", "error: " + ex.getMessage(), ex);
    }

    //RegisterActivity.login(username,password,getApplicationContext());

}

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 v  a 2  s  . 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.votingsystem.util.HttpHelper.java

public ResponseVS sendObjectMap(Map<String, Object> fileMap, String serverURL) throws Exception {
    log.info("sendObjectMap - serverURL: " + serverURL);
    ResponseVS responseVS = null;//from  w w w  . ja v a  2s.  c o m
    if (fileMap == null || fileMap.isEmpty())
        throw new Exception(ContextVS.getInstance().getMessage("requestWithoutFileMapErrorMsg"));
    HttpPost httpPost = null;
    CloseableHttpResponse response = null;
    ContentTypeVS responseContentType = null;
    try {
        httpPost = new HttpPost(serverURL);
        Set<String> fileNames = fileMap.keySet();
        MultipartEntity reqEntity = new MultipartEntity();
        for (String objectName : fileNames) {
            Object objectToSend = fileMap.get(objectName);
            if (objectToSend instanceof File) {
                File file = (File) objectToSend;
                log.info("sendObjectMap - fileName: " + objectName + " - filePath: " + file.getAbsolutePath());
                FileBody fileBody = new FileBody(file);
                reqEntity.addPart(objectName, fileBody);
            } else if (objectToSend instanceof byte[]) {
                byte[] byteArray = (byte[]) objectToSend;
                reqEntity.addPart(objectName, new ByteArrayBody(byteArray, objectName));
            }
        }
        httpPost.setEntity(reqEntity);
        response = httpClient.execute(httpPost);
        Header header = response.getFirstHeader("Content-Type");
        if (header != null)
            responseContentType = ContentTypeVS.getByName(header.getValue());
        log.info("----------------------------------------");
        log.info(response.getStatusLine().toString() + " - contentTypeVS: " + responseContentType
                + " - connManager stats: " + connManager.getTotalStats().toString());
        log.info("----------------------------------------");
        byte[] responseBytes = EntityUtils.toByteArray(response.getEntity());
        responseVS = new ResponseVS(response.getStatusLine().getStatusCode(), responseBytes,
                responseContentType);
        EntityUtils.consume(response.getEntity());
    } catch (Exception ex) {
        String statusLine = null;
        if (response != null)
            statusLine = response.getStatusLine().toString();
        log.log(Level.SEVERE, ex.getMessage() + " - StatusLine: " + statusLine, ex);
        responseVS = new ResponseVS(ResponseVS.SC_ERROR, ex.getMessage());
        if (httpPost != null)
            httpPost.abort();
    } finally {
        try {
            if (response != null)
                response.close();
        } catch (Exception ex) {
            log.log(Level.SEVERE, ex.getMessage(), ex);
        }
        return responseVS;
    }
}