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.alta189.deskbin.services.image.ImgurService.java

@Override
public String upload(File image) throws ImageServiceException {
    try {//ww w.ja v a2s  . c  om
        HttpPost post = new HttpPost(UPLOAD_URL);

        MultipartEntity entity = new MultipartEntity();
        entity.addPart("key", new StringBody(apikey, Charset.forName("UTF-8")));
        entity.addPart("type", new StringBody("file", Charset.forName("UTF-8")));
        FileBody fileBody = new FileBody(image);
        entity.addPart("image", fileBody);
        post.setEntity(entity);

        HttpResponse response = client.execute(post);
        if (response.getStatusLine().getStatusCode() != 200) {
            throw new ImageServiceException(
                    "Error accessing imgur. Status code: " + response.getStatusLine().getStatusCode());
        }
        String json = EntityUtils.toString(response.getEntity());
        JSONObject jsonObject = new JSONObject(json).getJSONObject("upload").getJSONObject("links");
        return jsonObject.getString("imgur_page");
    } catch (Exception e) {
        throw new ImageServiceException(e);
    }
}

From source file:key.access.manager.HttpHandler.java

public boolean sendImage(String url, String employeeId, File imageFile) throws IOException {
    String userHome = System.getProperty("user.home");
    HttpClient httpClient = new DefaultHttpClient();
    httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpPost httpPost = new HttpPost(url);
    FileBody fileBody = new FileBody(imageFile);
    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    reqEntity.addPart("fileToUpload", fileBody);
    reqEntity.addPart("employee_id", new StringBody(employeeId));

    httpPost.setEntity(reqEntity);//from w w w  .j ava  2s . c o m

    // execute HTTP post request
    HttpResponse response = httpClient.execute(httpPost);
    HttpEntity resEntity = response.getEntity();

    if (resEntity != null) {
        String responseStr = EntityUtils.toString(resEntity).trim();
        System.out.println(responseStr);
        return true;
    } else {
        return false;
    }
}

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

@Test
public void testPutAndGetFile() throws Exception {
    // Store a file in the repository
    String mediapackageId = "123";
    String elementId = "456";
    byte[] bytesFromPost = IOUtils
            .toByteArray(getClass().getClassLoader().getResourceAsStream("opencast_header.gif"));
    InputStream in = getClass().getClassLoader().getResourceAsStream("opencast_header.gif");
    String fileName = "our_logo.gif"; // Used to simulate a file upload
    MultipartEntity postEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    postEntity.addPart("file", new InputStreamBody(in, fileName));
    HttpPost post = new HttpPost(BASE_URL + "/files/mediapackage/" + mediapackageId + "/" + elementId);
    post.setEntity(postEntity);/*from   w ww  .  j  a v  a2 s.  co m*/
    HttpResponse response = client.execute(post);
    HttpEntity responseEntity = response.getEntity();
    String stringResponse = EntityUtils.toString(responseEntity);
    String expectedResponse = BASE_URL + "/files/mediapackage/" + mediapackageId + "/" + elementId + "/"
            + fileName;
    Assert.assertEquals(expectedResponse, stringResponse);

    // Get the file back from the repository
    HttpGet get = new HttpGet(BASE_URL + "/files/mediapackage/" + mediapackageId + "/" + elementId);
    HttpResponse getResponse = client.execute(get);
    byte[] bytesFromGet = IOUtils.toByteArray(getResponse.getEntity().getContent());

    // Ensure that the bytes that we posted are the same we received
    Assert.assertTrue(Arrays.equals(bytesFromGet, bytesFromPost));
}

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);/*from  w  ww  .  j av  a2  s .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:io.undertow.servlet.test.charset.ParameterCharacterEncodingTestCase.java

@Test
public void testMultipartCharacterEncoding() throws IOException {
    TestHttpClient client = new TestHttpClient();
    try {/*  w  w  w  .java 2  s  .c  o m*/
        String message = "abc?";
        String charset = "UTF-8";

        HttpPost post = new HttpPost(DefaultServer.getDefaultServerURL() + "/servletContext");

        MultipartEntity multipart = new MultipartEntity();
        multipart.addPart("charset", new StringBody(charset, Charset.forName(charset)));
        multipart.addPart("message", new StringBody(message, Charset.forName(charset)));
        post.setEntity(multipart);
        HttpResponse result = client.execute(post);
        Assert.assertEquals(StatusCodes.OK, result.getStatusLine().getStatusCode());
        String response = HttpClientUtils.readResponse(result);
        Assert.assertEquals(message, response);
    } finally {
        client.getConnectionManager().shutdown();
    }
}

From source file:bluej.collect.DataCollectorImpl.java

public static void edit(final Package pkg, final File path, final String source,
        final boolean includeOneLineEdits) {
    final Project proj = pkg.getProject();
    final ProjectDetails projDetails = new ProjectDetails(proj);
    final FileKey key = new FileKey(projDetails, CollectUtility.toPath(projDetails, path));
    final String anonSource = CodeAnonymiser.anonymise(source);
    final List<String> anonDoc = Arrays.asList(Utility.splitLines(anonSource));

    submitEvent(proj, pkg, EventName.EDIT, new Event() {

        private boolean dontReplace = false;

        //Edit solely within one line
        private boolean isOneLineDiff(Patch patch) {
            if (patch.getDeltas().size() > 1)
                return false;
            Delta theDelta = patch.getDeltas().get(0);
            return theDelta.getOriginal().size() == 1 && theDelta.getRevised().size() == 1;
        }//w  w  w  .  j a v  a  2 s .  c  o m

        @Override
        public MultipartEntity makeData(int sequenceNum, Map<FileKey, List<String>> fileVersions) {
            List<String> previousDoc = fileVersions.get(key);
            if (previousDoc == null)
                previousDoc = new ArrayList<String>(); // Diff against empty file

            MultipartEntity mpe = new MultipartEntity();

            Patch patch = DiffUtils.diff(previousDoc, anonDoc);

            if (patch.getDeltas().isEmpty() || (isOneLineDiff(patch) && !includeOneLineEdits)) {
                dontReplace = true;
                return null;
            }

            String diff = makeDiff(patch);

            mpe.addPart("source_histories[][content]", CollectUtility.toBody(diff));
            mpe.addPart("source_histories[][source_history_type]", CollectUtility.toBody("diff"));
            mpe.addPart("source_histories[][name]",
                    CollectUtility.toBody(CollectUtility.toPath(projDetails, path)));

            return mpe;
        }

        @Override
        public void success(Map<FileKey, List<String>> fileVersions) {
            if (!dontReplace) {
                fileVersions.put(key, anonDoc);
            }
        }
    });
}

From source file:com.networkmanagerapp.SettingBackgroundUploader.java

/**
 * Performs the file upload in the background
 * @throws FileNotFoundException, IOException, both caught internally. 
 * @param arg0 The intent to run in the background.
 *///www.ja v  a  2  s.  c o m
@Override
protected void onHandleIntent(Intent arg0) {
    configFilePath = arg0.getStringExtra("CONFIG_FILE_PATH");
    key = arg0.getStringExtra("KEY");
    value = arg0.getStringExtra("VALUE");
    mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    showNotification();
    try {
        fos = NetworkManagerMainActivity.getInstance().openFileOutput(this.configFilePath,
                Context.MODE_PRIVATE);
        String nameLine = "Name" + " = " + "\"" + this.key + "\"\n";
        String valueLine = "Value" + " = " + "\"" + this.value + "\"";
        fos.write(nameLine.getBytes());
        fos.write(valueLine.getBytes());
        fos.close();

        String password = PreferenceManager.getDefaultSharedPreferences(this).getString("password_preference",
                "");
        File f = new File(NetworkManagerMainActivity.getInstance().getFilesDir() + "/" + this.configFilePath);
        HttpHost targetHost = new HttpHost(
                PreferenceManager.getDefaultSharedPreferences(this).getString("ip_preference", "192.168.1.1"),
                1080, "http");
        DefaultHttpClient client = new DefaultHttpClient();
        client.getCredentialsProvider().setCredentials(
                new AuthScope(targetHost.getHostName(), targetHost.getPort()),
                new UsernamePasswordCredentials("root", password));
        HttpPost httpPost = new HttpPost("http://"
                + PreferenceManager.getDefaultSharedPreferences(NetworkManagerMainActivity.getInstance())
                        .getString("ip_preference", "192.168.1.1")
                + ":1080/cgi-bin/upload.php");
        MultipartEntity entity = new MultipartEntity();
        entity.addPart("file", new FileBody(f));
        httpPost.setEntity(entity);
        HttpResponse response = client.execute(httpPost);
        Log.d("upload", response.getStatusLine().toString());
    } catch (FileNotFoundException e) {
        Log.e("NETWORK_MANAGER_XU_FNFE", e.getLocalizedMessage());
    } catch (IOException e) {
        Log.e("NETWORK_MANAGER_XU_IOE", e.getLocalizedMessage());
    } finally {
        mNM.cancel(R.string.upload_service_started);
        stopSelf();
    }
}

From source file:org.jboss.test.capedwarf.blobstore.support.FileUploader.java

public String uploadFile(String uri, String partName, String filename, String mimeType, byte[] contents)
        throws URISyntaxException, IOException {
    HttpClient httpClient = new DefaultHttpClient();

    HttpPost post = new HttpPost(uri);
    MultipartEntity entity = new MultipartEntity();
    ByteArrayBody contentBody = new ByteArrayBody(contents, mimeType, filename);
    entity.addPart(partName, contentBody);
    post.setEntity(entity);/*from   w  w w.j av a2 s.  c o  m*/

    HttpResponse response = httpClient.execute(post);
    return EntityUtils.toString(response.getEntity());
}

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);/*  w ww  . j  a  v a2s. 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);/* w  w  w .ja  va  2  s.  c om*/
    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);
}