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:App.App.java

public static void main(String[] args) throws IOException {
    File inFile = new File("C:\\Data\\LogTest.java");
    FileInputStream fis = new FileInputStream(inFile);
    DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
    HttpPost httppost = new HttpPost("http://localhost:8080/rest_j2ee/rest/files/upload");
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("file", new InputStreamBody(fis, inFile.getName()));
    httppost.setEntity(entity);/*from   w  w w  .  ja  v a  2  s . c o  m*/
    HttpResponse response = httpclient.execute(httppost);
    int statusCode = response.getStatusLine().getStatusCode();
    HttpEntity responseEntity = response.getEntity();
    String responseString = EntityUtils.toString(responseEntity, "UTF-8");
    System.out.println("[" + statusCode + "] " + responseString);
}

From source file:org.dineth.shooter.client.Example.java

public static void main(String[] args) {

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://localhost:8080/upload");
    filename = "router.jpg";

    FileBody bin = new FileBody(new File(filename));
    StringBody fileName = null;//from  ww w  .  j ava 2s.  c  om
    try {
        fileName = new StringBody(filename);
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(Example.class.getName()).log(Level.SEVERE, null, ex);
    }

    MultipartEntity reqEntity = new MultipartEntity();
    reqEntity.addPart("file", bin);
    reqEntity.addPart("filename", fileName);
    httppost.setEntity(reqEntity);

    HttpResponse response = null;
    try {
        response = httpclient.execute(httppost);
    } catch (IOException ex) {
        Logger.getLogger(Example.class.getName()).log(Level.SEVERE, null, ex);
    }
    HttpEntity resEntity = response.getEntity();

}

From source file:com.dlmu.heipacker.crawler.examples.entity.mime.ClientMultipartFormPost.java

public static void main(String[] args) throws Exception {
    if (args.length != 1) {
        System.out.println("File path not given");
        System.exit(1);// ww w .ja v  a 2s  . c om
    }
    HttpClient httpclient = new DefaultHttpClient();
    try {
        HttpPost httppost = new HttpPost(
                "http://localhost:8080" + "/servlets-examples/servlet/RequestInfoExample");

        FileBody bin = new FileBody(new File(args[0]));
        StringBody comment = new StringBody("A binary file of some kind");

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("bin", bin);
        reqEntity.addPart("comment", comment);

        httppost.setEntity(reqEntity);

        System.out.println("executing request " + httppost.getRequestLine());
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (resEntity != null) {
            System.out.println("Response content length: " + resEntity.getContentLength());
        }
        EntityUtils.consume(resEntity);
    } finally {
        try {
            httpclient.getConnectionManager().shutdown();
        } catch (Exception ignore) {
        }
    }
}

From source file:com.tianya.ClientMultipartFormPost.java

public static void main(String[] args) throws Exception {

    /*//from ww w .  jav a  2s .  c om
     if (args.length != 1)  {
    System.out.println("File path not given");
    System.exit(1);
     }
     */

    HttpClient httpclient = new DefaultHttpClient();
    String posturl = "http://letushow.com/submit";

    preGet(httpclient);

    try {
        HttpPost httppost = new HttpPost(posturl);

        FileBody bin = new FileBody(new File("/Users/gypsai/Desktop/letushow/let.gif"));
        StringBody title = new StringBody("let");

        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("imgfile", bin);
        reqEntity.addPart("csrf_token", new StringBody(csrf_token));
        reqEntity.addPart("title", title);
        reqEntity.addPart("type", new StringBody("local"));

        httppost.setEntity(reqEntity);

        System.out.println("executing request " + httppost.getRequestLine());
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity resEntity = response.getEntity();

        System.out.println("----------------------------------------");
        System.out.println(response.getStatusLine());
        if (resEntity != null) {
            // System.out.println("Response content length: " + resEntity.getContentLength());
            System.out.println(iotostring(response.getEntity().getContent()));
        }
        EntityUtils.consume(resEntity);
    } finally {
        try {
            httpclient.getConnectionManager().shutdown();
        } catch (Exception ignore) {
        }
    }
}

From source file:httpclient.UploadAction.java

public static void main(String[] args) throws FileNotFoundException {
    File targetFile1 = new File("F:\\2.jpg");
    // File targetFile2 = new File("F:\\1.jpg");
    FileInputStream fis1 = new FileInputStream(targetFile1);
    // FileInputStream fis2 = new FileInputStream(targetFile2);
    // String targetURL =
    // "http://static.fangbiandian.com.cn/round_server/upload/uploadFile.do";
    String targetURL = "http://www.fangbiandian.com.cn/round_server/user/updateUserInfo.do";
    HttpPost filePost = new HttpPost(targetURL);
    try {/*  w ww.  ja  v  a  2s.c o  m*/
        // ?????
        HttpClient client = new DefaultHttpClient();
        // FormBodyPart fbp1 = new FormBodyPart("file1", new
        // FileBody(targetFile1));
        // FormBodyPart fbp2 = new FormBodyPart("file2", new
        // FileBody(targetFile2));
        // FormBodyPart fbp3 = new FormBodyPart("file3", new
        // FileBody(targetFile3));
        // List<FormBodyPart> picList = new ArrayList<FormBodyPart>();
        // picList.add(fbp1);
        // picList.add(fbp2);
        // picList.add(fbp3);
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap.put("userId", "65478A5CD8D20C3807EE16CF22AF8A17");
        Map<String, Object> map = new HashMap<String, Object>();
        String jsonStr = JSON.toJSONString(paramMap);
        map.put("cid", 321);
        map.put("request", jsonStr);
        String jsonString = JSON.toJSONString(map);
        MultipartEntity multiEntity = new MultipartEntity();
        Charset charset = Charset.forName("UTF-8");
        multiEntity.addPart("request", new StringBody(jsonString, charset));
        multiEntity.addPart("photo", new InputStreamBody(fis1, "2.jpg"));
        // multiEntity.addPart("licenseUrl", new InputStreamBody(fis2,
        // "1.jpg"));
        filePost.setEntity(multiEntity);
        HttpResponse response = client.execute(filePost);
        int code = response.getStatusLine().getStatusCode();
        System.out.println(code);
        if (HttpStatus.SC_OK == code) {
            System.out.println("?");
            HttpEntity entity = response.getEntity();
            if (entity != null) {
                InputStream instream = entity.getContent();
                try {
                    // do something useful
                    BufferedReader reader = new BufferedReader(new InputStreamReader(instream));
                    String str = null;
                    while ((str = reader.readLine()) != null) {
                        System.out.println(str);
                    }
                } finally {
                    instream.close();
                }
            }
        } else {
            System.out.println("");
        }
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        filePost.releaseConnection();
    }
}

From source file:org.craftercms.social.UCGRestServicesTest.java

public static void main(String[] args) throws Exception {

    ProfileClient profileRestClient = new ProfileRestClientImpl();

    String token = profileRestClient.getAppToken("craftersocial", "craftersocial");
    Tenant tenant = profileRestClient.getTenantByName(token, "testing");
    String ticket = profileRestClient.getTicket(token, "admin", "admin", tenant.getId());
    List<NameValuePair> qparams = new ArrayList<NameValuePair>();
    qparams.add(new BasicNameValuePair("ticket", ticket));
    qparams.add(new BasicNameValuePair("target", "testing"));

    qparams.add(new BasicNameValuePair("textContent", "Content"));

    URI uri = URIUtils.createURI("http", "localhost", 8080, "crafter-social/api/1/ugc/" + "create.json",
            URLEncodedUtils.format(qparams, HTTP.UTF_8), null);

    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(uri);
    File file = new File(
            "/Users/alvarogonzalez/development/projects/crafter-social/rest/src/test/resources/test.txt");
    MultipartEntity me = new MultipartEntity();

    //The usual form parameters can be added this way
    //me.addPart("fileDescription", new StringBody(fileDescription != null ? fileDescription : "")) ;
    //multiPartEntity.addPart("fileName", new StringBody(fileName != null ? fileName : file.getName())) ;

    /*Need to construct a FileBody with the file that needs to be attached and specify the mime type of the file. Add the fileBody to the request as an another part.
    This part will be considered as file part and the rest of them as usual form-data parts*/
    FileBody fileBody = new FileBody(file, "application/octect-stream");
    //me.addPart("ticket", new StringBody(token)) ;
    //me.addPart("target", new StringBody("my-test")) ;
    me.addPart("attachments", fileBody);

    httppost.setEntity(me);/*from  ww  w .j a  v a2  s . com*/
    httpclient.execute(httppost);

}

From source file:org.droidparts.net.http.worker.wrapper.HttpMimeWrapper.java

public static HttpEntity buildMultipartEntity(String name, String contentType, String fileName, InputStream is)
        throws IOException {
    byte[] data = IOUtils.readToByteArray(is);
    ContentBody contentBody;//from  w w w . jav  a 2 s.c  o  m
    if (contentType != null) {
        contentBody = new ByteArrayBody(data, contentType, fileName);
    } else {
        contentBody = new ByteArrayBody(data, fileName);
    }
    MultipartEntity entity = new MultipartEntity();
    entity.addPart(name, contentBody);
    return entity;
}

From source file:org.opencastproject.remotetest.server.resource.FilesResources.java

public static HttpResponse postFile(TrustedHttpClient client, String mediaPackageID,
        String mediaPackageElementID, String media) throws Exception {
    HttpPost post = new HttpPost(
            getServiceUrl() + "mediapackage/" + mediaPackageElementID + "/" + mediaPackageElementID);
    MultipartEntity entity = new MultipartEntity();
    entity.addPart("file", new FileBody(new File(media)));
    post.setEntity(entity);/*from  w ww. j a  v  a  2s .co m*/
    return client.execute(post);
}

From source file:Technique.PostFile.java

public static void upload(String files) throws Exception {

    String userHome = System.getProperty("user.home");
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpPost httppost = new HttpPost("http://localhost/image/up.php");
    File file = new File(files);
    MultipartEntity mpEntity = new MultipartEntity();
    ContentBody contentFile = new FileBody(file);
    mpEntity.addPart("userfile", contentFile);
    httppost.setEntity(mpEntity);/* ww  w  .  j a v  a  2  s  .c  o  m*/
    System.out.println("executing request " + httppost.getRequestLine());
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();

    if (!(response.getStatusLine().toString()).equals("HTTP/1.1 200 OK")) {
        // Successfully Uploaded
    } else {
        // Did not upload. Add your logic here. Maybe you want to retry.
    }
    System.out.println(response.getStatusLine());
    if (resEntity != null) {
        System.out.println(EntityUtils.toString(resEntity));
    }
    if (resEntity != null) {
        resEntity.consumeContent();
    }
    httpclient.getConnectionManager().shutdown();
}

From source file:org.energyos.espi.datacustodian.console.ImportUsagePoint.java

public static void upload(String filename, String url, HttpClient client) throws IOException {
    HttpPost post = new HttpPost(url);
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    File file = new File(filename);
    entity.addPart("file", new FileBody(((File) file), "application/rss+xml"));

    post.setEntity(entity);/*from   w  w w  .  j a v  a 2 s. c  o  m*/

    client.execute(post);
}