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

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

Introduction

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

Prototype

public MultipartEntity() 

Source Link

Usage

From source file:org.opencastproject.remotetest.server.MultiPartTest.java

@Test
public void testMultiPartPost() throws Exception {

    String mp = "<oc:mediapackage xmlns:oc=\"http://mediapackage.opencastproject.org\" id=\"10.0000/1\" start=\"2007-12-05T13:40:00\" duration=\"1004400000\"></oc:mediapackage>";

    InputStream is = null;//from  w ww  . j  a  va  2 s .  c o m
    try {
        is = getClass().getResourceAsStream("/av.mov");
        InputStreamBody fileContent = new InputStreamBody(is, "av.mov");
        MultipartEntity mpEntity = new MultipartEntity();
        mpEntity.addPart("mediaPackage", new StringBody(mp));
        mpEntity.addPart("flavor", new StringBody("presentation/source"));
        mpEntity.addPart("userfile", fileContent);
        HttpPost httppost = new HttpPost(BASE_URL + "/ingest/addAttachment");
        httppost.setEntity(mpEntity);
        HttpResponse response = httpClient.execute(httppost);
        Assert.assertEquals(200, response.getStatusLine().getStatusCode());
    } finally {
        IOUtils.closeQuietly(is);
    }
}

From source file:cn.clxy.upload.ApacheHCUploader.java

private void post(Map<String, ContentBody> params) {

    HttpPost post = new HttpPost(Config.url);
    MultipartEntity entity = new MultipartEntity();
    for (Entry<String, ContentBody> e : params.entrySet()) {
        entity.addPart(e.getKey(), e.getValue());
    }/*from   w  ww . j  a  v a  2 s.co  m*/
    post.setEntity(entity);

    try {
        HttpResponse response = client.execute(post);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            throw new RuntimeException("Upload failed.");
        }
    } catch (Exception e) {
        post.abort();
        throw new RuntimeException(e);
    } finally {
        post.releaseConnection();
    }
}

From source file:com.lambdasoup.panda.PandaHttp.java

static String postFile(String url, Map<String, String> params, Properties properties, File file) {
    Map<String, String> sParams = signedParams("POST", url, params, properties);
    String flattenParams = canonicalQueryString(sParams);
    String requestUrl = "http://" + properties.getProperty("api-host") + ":80/v2" + url + "?" + flattenParams;

    HttpPost httpPost = new HttpPost(requestUrl);
    String stringResponse = null;
    FileBody bin = new FileBody(file, "application/octet-stream");
    try {/*  w w  w .  j  a v a 2 s  . co m*/
        MultipartEntity entity = new MultipartEntity();
        entity.addPart("file", bin);

        httpPost.setEntity(entity);

        DefaultHttpClient httpclient = new DefaultHttpClient();

        HttpResponse response = httpclient.execute(httpPost);
        stringResponse = EntityUtils.toString(response.getEntity());

    } catch (UnsupportedEncodingException ex) {
        ex.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return stringResponse;
}

From source file:org.jcommon.com.facebook.utils.FacebookRequest.java

public void run() {
    HttpClient httpclient = new DefaultHttpClient();
    try {//from w w w .  j a  va  2  s .c o m
        logger.info(Integer.valueOf("file size:" + this.in != null ? this.in.available() : 0));
        HttpPost httppost = new HttpPost(this.url_);
        MultipartEntity reqEntity = new MultipartEntity();

        FormBodyPart stream_part = new FormBodyPart(this.stream_name,
                new InputStreamBody(this.in, this.file_name));

        reqEntity.addPart(stream_part);
        for (int i = 0; i < this.keys.length; i++) {
            reqEntity.addPart(this.keys[i], new StringBody(this.values[i]));
        }

        httppost.setEntity(reqEntity);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();
        StatusLine status_line = response.getStatusLine();
        int responseCode = status_line.getStatusCode();

        BufferedReader http_reader = null;
        if (responseCode == 200) {
            http_reader = new BufferedReader(new InputStreamReader(resEntity.getContent(), "utf-8"));
            String line = null;
            while ((line = http_reader.readLine()) != null) {
                this.sResult.append(line);
            }
            if (this.listener_ != null)
                this.listener_.onSuccessful(this, this.sResult);
        } else if (responseCode >= 400) {
            http_reader = new BufferedReader(new InputStreamReader(resEntity.getContent(), "utf-8"));
            String line = null;
            while ((line = http_reader.readLine()) != null) {
                this.sResult.append(line);
            }
            logger.info("[URL][response][failure]" + this.sResult);
            if (this.listener_ != null)
                this.listener_.onFailure(this, this.sResult);
        } else {
            this.sResult.append("[URL][response][failure][code : " + responseCode + " ]");
            if (this.listener_ != null)
                this.listener_.onFailure(this, this.sResult);
            logger.info("[URL][response][failure][code : " + responseCode + " ]");
        }
        EntityUtils.consume(resEntity);
    } catch (UnsupportedEncodingException e) {
        logger.warn("[HttpReqeust] error:" + this.url_ + "\n" + e);
        if (this.listener_ != null)
            this.listener_.onException(this, e);
    } catch (ClientProtocolException e) {
        logger.warn("[HttpReqeust] error:" + this.url_ + "\n" + e);
        if (this.listener_ != null)
            this.listener_.onException(this, e);
    } catch (IOException e) {
        logger.warn("[HttpReqeust] error:" + this.url_ + "\n" + e);
        if (this.listener_ != null)
            this.listener_.onException(this, e);
    } finally {
        try {
            httpclient.getConnectionManager().shutdown();
        } catch (Exception ignore) {
        }
    }
}

From source file:cn.clxy.codes.upload.ApacheHCUploader.java

private void post(Map<String, ContentBody> params) {

    HttpPost post = new HttpPost(Config.URL);
    MultipartEntity entity = new MultipartEntity();
    for (Entry<String, ContentBody> e : params.entrySet()) {
        entity.addPart(e.getKey(), e.getValue());
    }/*from  ww w  . j a v a2  s .  c om*/
    post.setEntity(entity);

    try {
        HttpResponse response = client.execute(post);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            throw new RuntimeException("Upload failed.");
        }
    } catch (Exception e) {
        post.abort();
        throw new RuntimeException(e);
    } finally {
        post.releaseConnection();
    }
}

From source file:ca.mcgill.hs.uploader.UploadThread.java

/**
 * Executes the upload in a separate thread
 *///from   w w  w. jav a  2  s.c  o  m

@Override
public void run() {
    Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
    int finalStatus = Constants.STATUS_UNKNOWN_ERROR;
    boolean countRetry = false;
    int retryAfter = 0;
    AndroidHttpClient client = null;
    PowerManager.WakeLock wakeLock = null;
    String filename = null;

    http_request_loop: while (true) {
        try {
            final PowerManager pm = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
            wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, Constants.TAG);
            wakeLock.acquire();

            filename = mInfo.mFileName;
            final File file = new File(filename);
            if (!file.exists()) {
                Log.e(Constants.TAG, "file" + filename + " is to be uploaded, but cannot be found.");
                finalStatus = Constants.STATUS_FILE_ERROR;
                break http_request_loop;
            }
            client = AndroidHttpClient.newInstance(Constants.DEFAULT_USER_AGENT, mContext);
            Log.v(Constants.TAG, "initiating upload for " + mInfo.mUri);
            final HttpPost request = new HttpPost(Constants.UPLOAD_URL);
            request.addHeader("MAC", NetworkHelper.getMacAddress(mContext));

            final MultipartEntity mpEntity = new MultipartEntity();
            mpEntity.addPart("uploadedfile", new FileBody(file, "binary/octet-stream"));
            request.setEntity(mpEntity);

            HttpResponse response;
            try {
                response = client.execute(request);
                final HttpEntity resEntity = response.getEntity();

                String responseMsg = null;
                if (resEntity != null) {
                    responseMsg = EntityUtils.toString(resEntity);
                    Log.i(Constants.TAG, "Server Response: " + responseMsg);
                }
                if (resEntity != null) {
                    resEntity.consumeContent();
                }

                if (!responseMsg.contains("SUCCESS 0x64asv65")) {
                    Log.i(Constants.TAG, "Server Response: " + responseMsg);
                }
            } catch (final IllegalArgumentException e) {
                finalStatus = Constants.STATUS_BAD_REQUEST;
                request.abort();
                break http_request_loop;
            } catch (final IOException e) {
                if (!NetworkHelper.isNetworkAvailable(mContext)) {
                    finalStatus = Constants.STATUS_RUNNING_PAUSED;
                } else if (mInfo.mNumFailed < Constants.MAX_RETRIES) {
                    finalStatus = Constants.STATUS_RUNNING_PAUSED;
                    countRetry = true;
                } else {
                    Log.d(Constants.TAG, "IOException trying to excute request for " + mInfo.mUri + " : " + e);
                    finalStatus = Constants.STATUS_HTTP_DATA_ERROR;
                }
                request.abort();
                break http_request_loop;
            }

            final int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 503 && mInfo.mNumFailed < Constants.MAX_RETRIES) {
                Log.v(Constants.TAG, "got HTTP response code 503");
                finalStatus = Constants.STATUS_RUNNING_PAUSED;
                countRetry = true;

                retryAfter = Constants.MIN_RETRY_AFTER;
                retryAfter += NetworkHelper.sRandom.nextInt(Constants.MIN_RETRY_AFTER + 1);
                retryAfter *= 1000;
                request.abort();
                break http_request_loop;
            } else {
                finalStatus = Constants.STATUS_SUCCESS;
            }
            break;
        } catch (final RuntimeException e) {
            finalStatus = Constants.STATUS_UNKNOWN_ERROR;
        } finally {
            mInfo.mHasActiveThread = false;
            if (wakeLock != null) {
                wakeLock.release();
                wakeLock = null;
            }
            if (client != null) {
                client.close();
                client = null;
            }
            if (finalStatus == Constants.STATUS_SUCCESS) {
                // TODO: Move the file.
            }
        }
    }

}

From source file:org.n52.sir.IT.HarvestScheduleIT.java

@Before
public void uploadAFileAndRetrieveScriptId() throws ClientProtocolException, IOException {
    File harvestScript = new File(ClassLoader.getSystemResource("Requests/randomSensor.js").getFile());
    PostMethod method = new PostMethod("http://localhost:8080/OpenSensorSearch/script/submit");
    Part[] parts = new Part[] { new StringPart("user", "User"), new FilePart("file", harvestScript) };
    method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
    MultipartEntity multipartEntity = new MultipartEntity();
    // upload the file
    multipartEntity.addPart("file", new FileBody(harvestScript));
    multipartEntity.addPart("user", new StringBody("User"));
    HttpPost post = new HttpPost("http://localhost:8080/OpenSensorSearch/script/submit");
    post.setEntity(multipartEntity);// w w  w  . j  ava  2s  .  co  m
    org.apache.http.client.HttpClient client = new DefaultHttpClient();
    HttpResponse resp = client.execute(post);
    int responseCode = resp.getStatusLine().getStatusCode();

    assertEquals(responseCode, 200);
    StringBuilder response = new StringBuilder();
    BufferedReader reader = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
    String s = null;
    while ((s = reader.readLine()) != null)
        response.append(s);

    int scriptId = Integer.parseInt(response.toString());

    System.setProperty(SCRIPT_ID, scriptId + "");
}

From source file:org.n52.sir.harvest.ScheduleBinding.java

public void testBinding() throws HttpException, IOException, InterruptedException, SolrServerException {
    File harvestScript = new File(ClassLoader.getSystemResource("Requests/randomSensor.js").getFile());
    PostMethod method = new PostMethod("http://localhost:8080/SIR/harvest/script/submit");
    Part[] parts = new Part[] { new StringPart("user", "testUser"), new FilePart("file", harvestScript) };
    method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
    MultipartEntity multipartEntity = new MultipartEntity();
    //upload the file
    multipartEntity.addPart("file", new FileBody(harvestScript));
    multipartEntity.addPart("user", new StringBody("testUserTest"));
    HttpPost post = new HttpPost("http://localhost:8080/SIR/harvest/script/submit");
    post.setEntity(multipartEntity);/*from w w  w.  j  a v a  2s . c  o m*/
    org.apache.http.client.HttpClient client = new DefaultHttpClient();
    HttpResponse resp = client.execute(post);
    int responseCode = resp.getStatusLine().getStatusCode();

    assertEquals(responseCode, 200);

    StringBuilder response = new StringBuilder();
    BufferedReader reader = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
    String s = null;
    while ((s = reader.readLine()) != null)
        response.append(s);

    int scriptId = Integer.parseInt(response.toString());

    //now do a scheduling

    StringBuilder scheduleRequest = new StringBuilder();
    scheduleRequest.append("http://localhost:8080/SIR/harvest/script/schedule");
    scheduleRequest.append("?id=");
    scheduleRequest.append(scriptId);
    Date d = new Date();
    scheduleRequest.append("&date=" + (d.getTime() + (10 * 1000)));

    HttpGet get = new HttpGet(scheduleRequest.toString());
    resp = new DefaultHttpClient().execute(get);

    assertEquals(resp.getStatusLine().getStatusCode(), 200);

    Thread.sleep(10 * 1000);

    SOLRSearchSensorDAO DAO = new SOLRSearchSensorDAO();
    Collection<SirSearchResultElement> results = DAO.searchByContact(randomString);

    assertTrue(results.size() > 0);

    new SolrConnection().deleteByQuery("contacts:" + randomString);
}

From source file:org.n52.oss.IT.harvest.ScheduleBinding.java

public void testBinding() throws HttpException, IOException, InterruptedException, SolrServerException {
    File harvestScript = new File(ClassLoader.getSystemResource("Requests/randomSensor.js").getFile());
    PostMethod method = new PostMethod("http://localhost:8080/SIR/harvest/script/submit");
    Part[] parts = new Part[] { new StringPart("user", "testUser"), new FilePart("file", harvestScript) };
    method.setRequestEntity(new MultipartRequestEntity(parts, method.getParams()));
    MultipartEntity multipartEntity = new MultipartEntity();
    //upload the file
    multipartEntity.addPart("file", new FileBody(harvestScript));
    multipartEntity.addPart("user", new StringBody("testUserTest"));
    HttpPost post = new HttpPost("http://localhost:8080/SIR/harvest/script/submit");
    post.setEntity(multipartEntity);/*ww w . jav  a  2s .  com*/
    org.apache.http.client.HttpClient client = new DefaultHttpClient();
    HttpResponse resp = client.execute(post);
    int responseCode = resp.getStatusLine().getStatusCode();

    assertEquals(responseCode, 200);

    StringBuilder response = new StringBuilder();
    BufferedReader reader = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
    String s = null;
    while ((s = reader.readLine()) != null)
        response.append(s);

    int scriptId = Integer.parseInt(response.toString());

    //now do a scheduling

    StringBuilder scheduleRequest = new StringBuilder();
    scheduleRequest.append("http://localhost:8080/SIR/harvest/script/schedule");
    scheduleRequest.append("?id=");
    scheduleRequest.append(scriptId);
    Date d = new Date();
    scheduleRequest.append("&date=" + (d.getTime() + (10 * 1000)));

    HttpGet get = new HttpGet(scheduleRequest.toString());
    resp = new DefaultHttpClient().execute(get);

    assertEquals(resp.getStatusLine().getStatusCode(), 200);

    Thread.sleep(10 * 1000);

    SolrConnection c = new SolrConnection("http://localhost:8983/solr", 2000);
    SOLRSearchSensorDAO dao = new SOLRSearchSensorDAO(c);
    Collection<SirSearchResultElement> results = dao.searchByContact(randomString);

    assertTrue(results.size() > 0);

    // FIXME use transactional delete operation, or just use a mocked up database
    c.deleteSensor("contacts:" + randomString);
}

From source file:org.andrico.andjax.http.HttpMessageFactory.java

/**
 * Create a new http uri request with more standard datatypes.
 * //  www .j av  a2s .  c  om
 * @param url The url to push the request to.
 * @param params String parameters to pass in the post.
 * @throws URISyntaxException
 */
public HttpMessage create(String url, Map<String, String> params) throws URISyntaxException {
    MultipartEntity multipartEntity = null;
    if (params != null) {
        multipartEntity = new MultipartEntity();
        for (final String key : params.keySet()) {
            try {
                multipartEntity.addPart(key, new StringBody(params.get(key)));
            } catch (final UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    return this.createFromParts(url, multipartEntity);
}