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(final HttpMultipartMode mode) 

Source Link

Usage

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);/* w  w w .  j av  a2  s . c  o m*/

    client.execute(post);
}

From source file:org.artags.android.app.util.http.HttpUtil.java

/**
 * Post data and attachements/*from   ww  w  .  jav  a 2s  . c  o  m*/
 * @param url The POST url
 * @param params Parameters
 * @param files Files
 * @return The return value
 * @throws HttpException If an error occurs
 */
public static String post(String url, HashMap<String, String> params, HashMap<String, File> files)
        throws HttpException {
    String ret = "";
    try {
        HttpClient client = new DefaultHttpClient();

        HttpPost post = new HttpPost(url);

        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        for (String key : files.keySet()) {
            FileBody bin = new FileBody(files.get(key));
            reqEntity.addPart(key, bin);
        }

        for (String key : params.keySet()) {
            String val = params.get(key);

            reqEntity.addPart(key, new StringBody(val, Charset.forName("UTF-8")));
        }
        post.setEntity(reqEntity);
        HttpResponse response = client.execute(post);

        HttpEntity resEntity = response.getEntity();
        if (resEntity != null) {
            ret = EntityUtils.toString(resEntity);
            Log.i("ARTags:HttpUtil:Post:Response", ret);
        }

        //return response;
    } catch (Exception e) {
        Log.e("ARTags:HttpUtil", "Error : " + e.getMessage());
        throw new HttpException(e.getMessage());
    }
    return ret;
}

From source file:net.bither.api.UploadAvatarApi.java

@Override
public HttpEntity getHttpEntity() throws Exception {
    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    multipartEntity.addPart(FILE_KEY, new FileBody(this.mFile));
    return multipartEntity;
}

From source file:org.overlord.sramp.governance.workflow.Multipart.java

public void post(HttpClient httpclient, URI uri, Map<String, Object> parameters)
        throws IOException, WorkflowException {
    MultipartEntity multiPartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    for (String key : parameters.keySet()) {
        ContentBody content = null;/*  w  w  w  . j a  va 2s.  com*/
        Object param = parameters.get(key);
        if (param instanceof String) {
            StringBody stringBody = new StringBody((String) param, "text/plain", Charset.forName("UTF-8")); //$NON-NLS-1$ //$NON-NLS-2$
            content = stringBody;
        } else {
            //turn object into byteArray, or it also supports InputStreamBody or FileBody
            ByteArrayBody byteBody = new ByteArrayBody(null, key);
            content = byteBody;
        }
        multiPartEntity.addPart(key, content);
    }
    HttpPost httpPost = new HttpPost(uri);
    httpPost.setEntity(multiPartEntity);
    HttpResponse response = httpclient.execute(httpPost);
    InputStream is = response.getEntity().getContent();
    String responseStr = IOUtils.toString(is);
    if (response.getStatusLine().getStatusCode() == 200 || response.getStatusLine().getStatusCode() == 201) {
        logger.debug(responseStr);
    } else {
        throw new WorkflowException(
                "Workflow ERROR - HTTP STATUS CODE " + response.getStatusLine().getStatusCode() + ". " //$NON-NLS-1$ //$NON-NLS-2$
                        + response.getStatusLine().getReasonPhrase() + ". " + responseStr); //$NON-NLS-1$
    }
    is.close();
}

From source file:hpcc.hut.edu.vn.ocr.ocrserviceconnector.HpccOcrServiceConnector.java

public static String postToOcrService(byte[] data, int size, int imgw, int imgh, String lang, int psm,
        boolean isPrePostProcess) {
    System.out.println("Sent data: w = " + imgw + ", h = " + imgh + ", psm = " + psm + ", process: "
            + isPrePostProcess + ", with lang: " + lang);
    String result = "";

    try {/*from   www  .  ja va 2 s. co m*/
        HttpParams httpParamenters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParamenters, 30000);
        DefaultHttpClient httpClient = new DefaultHttpClient(httpParamenters);
        HttpPost postRequest = new HttpPost(HOST);

        ByteArrayBody bab = new ByteArrayBody(data, "input.jpg");
        MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        reqEntity.addPart("image", bab);
        reqEntity.addPart("size", new StringBody("" + size)); // size to
        // check if
        // decompress
        // fail
        reqEntity.addPart("width", new StringBody("" + imgw));
        reqEntity.addPart("height", new StringBody("" + imgh));
        reqEntity.addPart("lang", new StringBody(lang));
        reqEntity.addPart("psm", new StringBody("" + psm));
        reqEntity.addPart("process", new StringBody("" + isPrePostProcess));

        postRequest.setEntity(reqEntity);

        HttpResponse response = httpClient.execute(postRequest);
        BufferedReader reader = new BufferedReader(
                new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
        String sResponse;
        StringBuilder s = new StringBuilder();
        while ((sResponse = reader.readLine()) != null) {
            s = s.append(sResponse);
        }
        result = s.toString();
        System.out.println("result in Json: " + result);
    } catch (Exception e) {
        // handle exception here
        Log.e(e.getClass().getName(), e.getMessage());
        return null;
    }
    return result;

}

From source file:at.uni_salzburg.cs.ckgroup.cscpp.utils.HttpQueryUtils.java

public static String[] fileUpload(String uploadUrl, String name, byte[] byteArray) throws IOException {
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(uploadUrl);
    String paramName = "vehicle";
    String paramValue = name;//from ww w.jav a 2  s .c o  m

    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    entity.addPart(paramName, new InputStreamBody((new ByteArrayInputStream(byteArray)), "application/zip"));
    entity.addPart(paramName, new StringBody(paramValue, "text/plain", Charset.forName("UTF-8")));
    httppost.setEntity(entity);
    HttpResponse httpResponse = httpclient.execute(httppost);
    StatusLine statusLine = httpResponse.getStatusLine();
    String reason = statusLine.getReasonPhrase();
    int rc = statusLine.getStatusCode();
    String response = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
    httpclient.getConnectionManager().shutdown();
    return new String[] { String.valueOf(rc), reason, response };
}

From source file:com.devbliss.doctest.httpfactory.PostUploadWithoutRedirectImpl.java

public HttpPost createPostRequest(URI uri, Object payload) throws IOException {
    HttpPost httpPost = new HttpPost(uri);
    HttpParams params = new BasicHttpParams();
    params.setParameter(HttpConstants.HANDLE_REDIRECTS, false);
    httpPost.setParams(params);/*from w  w w. j  a  v  a  2  s  .  c  o  m*/

    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    entity.addPart(paramName, fileBodyToUpload);
    httpPost.setEntity(entity);

    return httpPost;
}

From source file:eg.nileu.cis.nilestore.main.HttpDealer.java

/**
 * Put./*  ww  w.  j a v  a 2  s.  c o m*/
 * 
 * @param filepath
 *            the filepath
 * @param url
 *            the url
 * @throws ClientProtocolException
 *             the client protocol exception
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 */
public static void put(String filepath, String url) throws ClientProtocolException, IOException {
    url = url + (url.endsWith("/") ? "" : "/") + "upload?t=json";
    HttpClient client = new DefaultHttpClient();
    client.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpPost post = new HttpPost(url);
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    File file = new File(filepath);
    final double filesize = file.length();

    ContentBody fbody = new FileBodyProgress(file, new ProgressListener() {

        @Override
        public void transfered(long bytes, float rate) {
            int percent = (int) ((bytes / filesize) * 100);
            String bar = ProgressUtils.progressBar("Uploading file to the gateway : ", percent, rate);
            System.err.print("\r" + bar);
            if (percent == 100) {
                System.err.println();
                System.err.println("wait the gateway is processing and saving your file");
            }
        }
    });

    entity.addPart("File", fbody);

    post.setEntity(entity);

    HttpResponse response = client.execute(post);

    if (response != null) {
        System.err.println(response.getStatusLine());
        HttpEntity ht = response.getEntity();
        String json = EntityUtils.toString(ht);
        JSONParser parser = new JSONParser();
        try {
            JSONObject obj = (JSONObject) parser.parse(json);
            System.out.println(obj.get("cap"));
        } catch (ParseException e) {
            System.err.println("Error during parsing the response: " + e.getMessage());
            System.exit(-1);
        }
    } else {
        System.err.println("Error: response = null");
    }

    client.getConnectionManager().shutdown();
}

From source file:com.urucas.services.JSONFileRequest.java

@SuppressWarnings("deprecation")
@Override/*ww  w .  j a v a 2s .com*/
protected String doInBackground(String... uri) {

    HttpClient httpclient = new DefaultHttpClient();

    // add request params
    StringBuffer url = new StringBuffer(uri[0]).append("?")
            .append(URLEncodedUtils.format(getParams(), "UTF-8"));

    HttpPost _post = new HttpPost(url.toString());
    HttpContext localContext = new BasicHttpContext();

    Log.i("url ---->", url.toString());

    MultipartEntity _entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    for (int index = 0; index < getParams().size(); index++) {
        try {
            _entity.addPart(getParams().get(index).getName(),
                    new StringBody(getParams().get(index).getValue()));
        } catch (UnsupportedEncodingException e) {
        }
    }

    _entity.addPart("imagen", new FileBody(file));

    _post.setEntity(_entity);

    HttpResponse response;

    String responseString = null;
    // execute
    try {
        response = httpclient.execute(_post, localContext);
        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            out.close();
            responseString = out.toString();
            if (isCancelled()) {
                rsh.onError("Task cancel");
            }

        } else {
            //Closes the connection.
            response.getEntity().getContent().close();
            Log.i("status", String.valueOf(statusLine.getStatusCode()));
            throw new IOException(statusLine.getReasonPhrase());
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
        //rsh.onError(e.getMessage());
    } catch (IOException e) {
        e.printStackTrace();
        //rsh.onError(e.getMessage());      
    }
    return responseString;
}

From source file:de.vanita5.twittnuker.util.shortener.TweetShortenerUtils.java

/**
 * Shorten long tweets with hotot.in/*from  w ww .j  av  a  2 s  . com*/
 * @param context
 * @param text
 * @param accounts
 * @return shortened tweet
 */
public static String shortWithHototin(final Context context, final String text, final Account[] accounts) {

    String screen_name = null;
    String avatar_url = null;

    if (accounts != null && accounts.length > 0) {
        screen_name = getAccountScreenName(context, accounts[0].account_id);
        avatar_url = getAccountProfileImage(context, accounts[0].account_id);
        avatar_url = avatar_url != null && !avatar_url.isEmpty() ? avatar_url : DEFAULT_AVATAR_URL;
    }

    try {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(HOTOTIN_URL);
        MultipartEntity requestEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        requestEntity.addPart(HOTOTIN_ENTITY_NAME, new StringBody(screen_name));
        requestEntity.addPart(HOTOTIN_ENTITY_AVATAR, new StringBody(avatar_url));
        requestEntity.addPart(HOTOTIN_ENTITY_TEXT, new StringBody(text, Charset.forName("UTF-8")));
        httpPost.setEntity(requestEntity);

        InputStream responseStream;
        BufferedReader br;

        HttpResponse response = httpClient.execute(httpPost);
        HttpEntity responseEntity = response.getEntity();
        responseStream = responseEntity.getContent();
        br = new BufferedReader(new InputStreamReader(responseStream));

        String responseLine = br.readLine();
        String tmpResponse = "";
        while (responseLine != null) {
            tmpResponse += responseLine + System.getProperty("line.separator");
            responseLine = br.readLine();
        }
        br.close();

        JSONObject jsonObject = new JSONObject(tmpResponse);

        String result = jsonObject.getString("text");

        return result;

    } catch (UnsupportedEncodingException e) {
        if (Utils.isDebugBuild())
            Log.e(LOG_TAG, e.getMessage());
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        if (Utils.isDebugBuild())
            Log.e(LOG_TAG, e.getMessage());
        e.printStackTrace();
    } catch (IOException e) {
        if (Utils.isDebugBuild())
            Log.e(LOG_TAG, e.getMessage());
        e.printStackTrace();
    } catch (JSONException e) {
        if (Utils.isDebugBuild())
            Log.e(LOG_TAG, e.getMessage());
        e.printStackTrace();
    }
    return null;
}