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:bluej.collect.DataCollectorImpl.java

/**
 * Submits an event and adds a source location.  This should be used if the file
 * is within the project (otherwise see submitEventWithClassLocation)
 * //from   w  w w .ja  v a 2s  .c o m
 * @param project
 * @param eventName
 * @param mpe You can pass null if you have no other data to give
 * @param sourceFile
 * @param lineNumber
 */
private static void submitEventWithLocalLocation(Project project, Package pkg, EventName eventName,
        MultipartEntity mpe, File sourceFile, int lineNumber) {
    if (mpe == null) {
        mpe = new MultipartEntity();
    }

    mpe.addPart("event[source_file_name]", CollectUtility.toBodyLocal(new ProjectDetails(project), sourceFile));
    mpe.addPart("event[line_number]", CollectUtility.toBody(lineNumber));

    submitEvent(project, pkg, eventName, new PlainEvent(mpe));
}

From source file:webcamcapture.WebCamCapture.java

void request(String url, String file_name) throws IOException {
    try {/* w  ww . j  av a  2  s .  c  o m*/
        HttpClient httpclient = new DefaultHttpClient();
        httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

        HttpPost httppost = new HttpPost(url);

        String file_path = "C:/Users/darshit/Documents/NetBeansProjects/WebCamCapture/" + file_name;
        File fileToUse = new File(file_path);
        FileBody data = new FileBody(fileToUse, "image/jpeg");

        System.out.println(Inet4Address.getLocalHost().getHostAddress());
        /*MultipartEntity mpEntity = new MultipartEntity();
        ContentBody cbFile = new FileBody(fileToUse, "image/jpeg");
        mpEntity.addPart("userfile", cbFile);*/

        // httppost.setEntity(mpEntity);
        //String file_type = "JPG" ;

        MultipartEntity reqEntity = new MultipartEntity();
        ContentBody cbFile = new FileBody(fileToUse, "image/jpeg");
        reqEntity.addPart("file", data);

        //reqEntity.addPart("file", cbFile);

        httppost.setEntity(reqEntity);
        //httppost.setEntity(mpEntity); 
        System.out.println("executing request " + httppost.getRequestLine());
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        InputStreamReader is;

        StringBuffer sb = new StringBuffer();
        System.out.println("finalResult " + sb.toString());
        //String line=null;
        /*while((reader.readLine())!=null){
        sb.append(line + "\n");
        }*/

        //StringBuilder sb = new StringBuilder();
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent()));
            String line = null;

            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        String result = sb.toString();
        System.out.println("finalResult " + sb.toString());
        // System.out.println( response ); 
        // String responseString = new BasicResponseHandler().handleResponse(response);
        //System.out.println();
    } catch (UnsupportedEncodingException ex) {
        Logger.getLogger(httpRequestSend.class.getName()).log(Level.SEVERE, null, ex);
        System.out.printf("dsf\n");
    }
}

From source file:com.onesite.commons.net.http.rest.client.RestClient.java

/**
 * Create a POST request to the given url posting the ContentBody to the content tag
 * URL = scheme://host:port/path?query_string
 * /*from w w  w.  j  av a 2 s. c o m*/
 * @param path
 * @param params
 * @param body
 * @return
 * @throws Exception
 */
public int post(String path, Map<String, String> params, ContentBody body) throws Exception {
    String url = this.generateEncodeURLString(path, params);

    DefaultHttpClient httpClient = new DefaultHttpClient();

    HttpPost request = new HttpPost(url);
    request.addHeader("accept", "application/json");

    MultipartEntity entity = new MultipartEntity();
    entity.addPart("content", body);
    request.setEntity(entity);

    try {
        HttpResponse response = httpClient.execute(this.target, request);

        try {
            this.processHttpResponse(response);
        } catch (Exception e) {
            log.error("Error processing HttpResponse from " + url);
            throw e;
        }
    } catch (Exception e) {
        log.error("Error occurred during calling to " + url);
        throw e;
    } finally {
        httpClient.getConnectionManager().shutdown();
    }

    return status;
}

From source file:com.dss886.nForumSDK.service.AttachmentService.java

/**
 * /*from w  w  w .j av  a  2s .  co m*/
* ??idid????
* @param boardName ????
* @param file 
* @return /?
* @throws JSONException
* @throws NForumException
* @throws IOException
*/
public Attachment addAttachment(String boardName, File file, ParamOption params)
        throws JSONException, NForumException, IOException {
    String url = host + "attachment/" + boardName + "/add";
    if (params.getParams().containsKey("id")) {
        url = url + "/" + params.getParams().get("id") + returnFormat + appkey;
    } else {
        url = url + returnFormat + appkey;
    }
    FileBody fileBody = new FileBody(file);
    MultipartEntity mEntity = new MultipartEntity();
    mEntity.addPart("file", fileBody);
    PostMethod postMethod = new PostMethod(httpClient, auth, url, mEntity);
    return Attachment.parse(postMethod.postJSON());
}

From source file:hu.sztaki.lpds.portal.util.stream.HttpClient.java

/**
 * File upload/*from w  ww . j av a2  s  .c o  m*/
 * @param pFile file to be uploaded
 * @param uploadName upload naem
 * @param pValue parameters used during the connection
 * @return http answer code
 * @throws java.lang.Exception communication error
 */
public int fileUpload(File pFile, String uploadName, Hashtable pValue) throws Exception {
    int res = 0;
    MultipartEntity reqEntity = new MultipartEntity();
    // file parameter
    if (uploadName != null) {
        FileBody bin = new FileBody(pFile);
        reqEntity.addPart(uploadName, bin);
    }
    //text parameters
    Enumeration<String> enm = pValue.keys();
    String key;
    while (enm.hasMoreElements()) {
        key = enm.nextElement();
        reqEntity.addPart(key, new StringBody("" + pValue.get(key)));
    }
    httpPost.setEntity(reqEntity);

    HttpResponse response = httpclient.execute(httpPost);
    HttpEntity resEntity = response.getEntity();
    res = response.getStatusLine().getStatusCode();
    close();
    return res;
}

From source file:com.google.appengine.tck.blobstore.support.FileUploader.java

public String uploadFile(String uri, String partName, String filename, String mimeType, byte[] contents,
        int expectedResponseCode) throws URISyntaxException, IOException {
    HttpClient httpClient = new DefaultHttpClient();
    try {/*from  ww  w  .  j  a  v a 2s .c om*/
        HttpPost post = new HttpPost(uri);
        MultipartEntity entity = new MultipartEntity();
        ByteArrayBody contentBody = new ByteArrayBody(contents, mimeType, filename);
        entity.addPart(partName, contentBody);
        post.setEntity(entity);
        HttpResponse response = httpClient.execute(post);
        String result = EntityUtils.toString(response.getEntity());
        int statusCode = response.getStatusLine().getStatusCode();
        Assert.assertEquals(String.format("Invalid response code, %s", statusCode), expectedResponseCode,
                statusCode);
        return result;
    } finally {
        httpClient.getConnectionManager().shutdown();
    }
}

From source file:com.ibm.watson.developer_cloud.visual_insights.v1.VisualInsights.java

/**
 * Upload a set of images as a zip file for visual insight extraction.
 *
 * @param imagesFile the images File/* ww  w.j a  v  a2  s  . c o m*/
 * @return the Summary of the collection's visual attributes
 */
public Summary getSummary(final File imagesFile) {
    if (imagesFile == null || !imagesFile.exists())
        throw new IllegalArgumentException("imagesFile can not be null or empty");

    MultipartEntity reqEntity = new MultipartEntity();
    reqEntity.addPart(FILE, new FileBody(imagesFile));
    Request request = Request.Post(SUMMARY_PATH).withEntity(reqEntity);

    return executeRequest(request, Summary.class);

}

From source file:net.ccghe.utils.Server.java

public static void UploadFile(String path, FileTransmitter transmitter) {
    MultipartEntity entity = new MultipartEntity();
    try {//from w  w w . j  a v a 2  s .co m
        entity.addPart("usr", new StringBody(user));
        entity.addPart("pwd", new StringBody(password));
        entity.addPart("cmd", new StringBody(CMD_UPLOAD_FILE));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }

    new UploadOneFile(path, serverURL, transmitter, entity);
}

From source file:eu.prestoprime.plugin.mserve.client.MServeClient.java

/**
 * Uploads a file on MServe and returns its fileID
 * /*from   w w  w  . j a  v  a 2  s  . c om*/
 * @param file
 * @return
 * @throws MServeException
 */
public String uploadFile(File file) throws MServeException {
    try {
        URL url = new URL(host + "/auths/" + serviceID + "/mfiles/");

        logger.debug("MServe URL: " + url.toString());

        HttpClient client = new DefaultHttpClient();
        HttpUriRequest request = new HttpPost(url.toString());
        request.setHeader("Accept", "application/json");

        MultipartEntity part = new MultipartEntity();
        part.addPart("file", new FileBody(file));

        ((HttpPost) request).setEntity(part);

        HttpEntity stream = client.execute(request).getEntity();
        InputStream istream = stream.getContent();

        BufferedReader buf = new BufferedReader(new InputStreamReader(istream));
        String line;
        StringBuffer sb = new StringBuffer();
        while (null != ((line = buf.readLine()))) {
            sb.append(line.trim());
        }
        buf.close();
        istream.close();

        logger.debug(sb.toString());

        JSONObject response = new JSONObject(sb.toString());

        return response.getString("id");
    } catch (MalformedURLException e) {
        throw new MServeException("Bad REST interface...");
    } catch (IOException e) {
        throw new MServeException("Unable to make IO...");
    } catch (JSONException e) {
        throw new MServeException("Bad JSON response...");
    }
}

From source file:com.rackspace.api.clients.veracode.DefaultVeracodeApiClient.java

private String uploadFile(File file, int buildVersion, String appId, String platfrom)
        throws VeracodeApiException {
    HttpPost post = new HttpPost(baseUri.resolve(UPLOAD));

    MultipartEntity entity = new MultipartEntity();

    try {//from  w w w . java 2s  .c  o m
        entity.addPart(new FormBodyPart("app_id", new StringBody(appId)));
        entity.addPart(new FormBodyPart("version", new StringBody(String.valueOf(buildVersion))));
        entity.addPart(new FormBodyPart("platform", new StringBody(platfrom)));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("The Request could not be made due to an encoding issue", e);

    }

    entity.addPart("file", new FileBody(file, "text/plain"));

    post.setEntity(entity);

    logger.println("Executing Request: " + post.getRequestLine());

    UploadResponse uploadResponse = null;

    try {
        uploadResponse = new UploadResponse(client.execute(post));
    } catch (IOException e) {
        throw new VeracodeApiException("The call to Veracode failed.", e);
    }

    return uploadResponse.getBuildId(buildVersion);
}