Example usage for org.apache.http.entity.mime HttpMultipartMode BROWSER_COMPATIBLE

List of usage examples for org.apache.http.entity.mime HttpMultipartMode BROWSER_COMPATIBLE

Introduction

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

Prototype

HttpMultipartMode BROWSER_COMPATIBLE

To view the source code for org.apache.http.entity.mime HttpMultipartMode BROWSER_COMPATIBLE.

Click Source Link

Usage

From source file:com.knurld.alphabank.com.knurld.alphabank.request.MultipartRequest.java

public MultipartRequest(String url, Response.Listener<String> listener, Response.ErrorListener errorListener,
        File file, Map<String, String> mStringPart, final Map<String, String> headerParams, String partName,
        MultipartProgressListener progLitener) {
    super(Method.POST, url, errorListener);
    this.mListener = listener;
    this.mFilePart = file;
    this.fileLength = file.length();
    this.mStringPart = mStringPart;
    this.headerParams = headerParams;
    this.FILE_PART_NAME = partName;
    this.multipartProgressListener = progLitener;

    entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    try {//from www . j ava2s  .  c o m
        entity.setCharset(CharsetUtils.get("UTF-8"));
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    buildMultipartEntity();
    httpentity = entity.build();
}

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

/**
 * Shorten long tweets with hotot.in/*www .  j  a  v a  2s .co  m*/
 * @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;
}

From source file:com.easycode.common.HttpUtil.java

public static byte[] httpPost(String url, List<FormItem> blist) throws Exception {
    byte[] ret = null;
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
            Charset.forName("UTF-8"));
    if (blist != null) {
        for (FormItem f : blist) {
            reqEntity.addPart(f.getName(), f.getCtx());
        }/* w w w  .ja  v a 2s  . c o  m*/
    }
    httppost.setEntity(reqEntity);
    HttpResponse response = httpclient.execute(httppost);

    HttpEntity resEntity = response.getEntity();

    if (resEntity != null) {
        InputStream tis = resEntity.getContent();

        java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
        byte[] bytes = new byte[1024];
        int len = 0;
        while ((len = tis.read(bytes)) > 0) {
            out.write(bytes, 0, len);
        }
        ret = out.toByteArray();
    }
    EntityUtils.consume(resEntity);
    try {
        httpclient.getConnectionManager().shutdown();
    } catch (Exception ignore) {
    }
    return ret;
}

From source file:uk.co.jarofgreen.cityoutdoors.API.BaseCall.java

protected void setUpCall(String url) {
    httpclient = new DefaultHttpClient();
    httppost = new HttpPost(informationNeededFromContext.getServerURL() + url);
    multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

    int userID = informationNeededFromContext.getSettings().getInt("userID", -1);
    if (userID > 0) {
        addDataToCall("userID", userID);
        addDataToCall("userToken", informationNeededFromContext.getSettings().getString("userToken", ""));
        isUserTokenAttached = true;/*from  w w  w.  j av  a2 s. co m*/
    }
}

From source file:fr.ippon.wip.http.request.MultipartRequestBuilder.java

public HttpRequestBase buildHttpRequest() throws URISyntaxException {
    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    try {/*from  w  w  w .  j a v a 2 s .c  o m*/
        for (DiskFileItem fileItem : files) {
            if (fileItem.isFormField())
                multipartEntity.addPart(fileItem.getFieldName(), new StringBody(new String(fileItem.get())));
            else {
                //               FileBody fileBody = new FileBody(fileItem.getStoreLocation(), fileItem.getName(), fileItem.getContentType(), fileItem.getCharSet());
                InputStreamBody fileBody = new InputStreamKnownSizeBody(fileItem.getInputStream(),
                        fileItem.get().length, fileItem.getContentType(), fileItem.getName());
                multipartEntity.addPart(fileItem.getFieldName(), fileBody);
            }
        }

        // some request may have additional parameters in a query string
        if (parameterMap != null)
            for (Entry<String, String> entry : parameterMap.entries())
                multipartEntity.addPart(entry.getKey(), new StringBody(entry.getValue()));

    } catch (Exception e) {
        e.printStackTrace();
    }

    HttpPost postRequest = new HttpPost(requestedURL);
    postRequest.setEntity(multipartEntity);
    return postRequest;
}

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);// w w  w. ja  v a2 s. c  o  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:com.revo.deployr.client.call.project.ProjectImportCall.java

/**
 * Internal use only, to execute call use RClient.execute().
 *///  w  w w  .j a  v a2  s.com
public RCoreResult call() {

    RCoreResultImpl pResult = null;

    try {

        HttpPost httpPost = new HttpPost(serverUrl + API);
        super.httpUriRequest = httpPost;

        List<NameValuePair> postParams = new ArrayList<NameValuePair>();
        postParams.add(new BasicNameValuePair("format", "json"));

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        entity.addPart("file", new InputStreamBody(((InputStream) fileStream), "application/zip"));
        entity.addPart("descr", new StringBody(descr, "text/plain", Charset.forName("UTF-8")));
        entity.addPart("format", new StringBody("json", "text/plain", Charset.forName("UTF-8")));

        httpPost.setEntity(entity);

        // set any custom headers on the request            
        for (Map.Entry<String, String> entry : httpHeaders.entrySet()) {
            httpPost.addHeader(entry.getKey(), entry.getValue());
        }

        HttpResponse response = httpClient.execute(httpPost);
        StatusLine statusLine = response.getStatusLine();
        HttpEntity responseEntity = response.getEntity();
        String markup = EntityUtils.toString(responseEntity);

        pResult = new RCoreResultImpl(response.getAllHeaders());
        pResult.parseMarkup(markup, API, statusLine.getStatusCode(), statusLine.getReasonPhrase());

    } catch (UnsupportedEncodingException ueex) {
        log.warn("ProjectImportCall: unsupported encoding exception.", ueex);
    } catch (IOException ioex) {
        log.warn("ProjectImportCall: io exception.", ioex);
    }

    return pResult;
}

From source file:com.kurento.test.recorder.RecorderIT.java

private void testRecord(String handler, int statusCode) throws IOException {
    // To follow redirect: .setRedirectStrategy(new LaxRedirectStrategy())
    HttpClient client = HttpClientBuilder.create().build();
    HttpPost post = new HttpPost("http://localhost:" + getServerPort() + "/kmf-content-api-test/" + handler);
    MultipartEntityBuilder multipartEntity = MultipartEntityBuilder.create();
    multipartEntity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    File file = new File("small");
    URL small = new URL(VideoURLs.map.get("small-webm"));
    FileUtils.copyURLToFile(small, file);
    FileBody fb = new FileBody(file);
    multipartEntity.addPart("file", fb);

    HttpEntity httpEntity = multipartEntity.build();
    post.setEntity(httpEntity);//from w  w w .j  av  a  2s.  c o  m

    EntityUtils.consume(httpEntity);
    HttpResponse response = client.execute(post);
    final int responseStatusCode = response.getStatusLine().getStatusCode();

    log.info("Response Status Code: {}", responseStatusCode);
    log.info("Deleting tmp file: {}", file.delete());

    Assert.assertEquals("HTTP response status code must be " + statusCode, statusCode, responseStatusCode);
}

From source file:com.revo.deployr.client.call.project.ProjectWorkspaceUploadCall.java

/**
 * Internal use only, to execute call use RClient.execute().
 *//*from   w w  w . ja  v  a 2s .c o m*/
public RCoreResult call() {

    RCoreResultImpl pResult = null;

    try {

        HttpPost httpPost = new HttpPost(serverUrl + API);
        super.httpUriRequest = httpPost;

        List<NameValuePair> postParams = new ArrayList<NameValuePair>();
        postParams.add(new BasicNameValuePair("format", "json"));

        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);

        entity.addPart("project", new StringBody(this.project, "text/plain", Charset.forName("UTF-8")));
        entity.addPart("name", new StringBody(this.name, "text/plain", Charset.forName("UTF-8")));
        entity.addPart("file", new InputStreamBody(((InputStream) fileStream), "application/zip"));
        entity.addPart("format", new StringBody("json", "text/plain", Charset.forName("UTF-8")));

        httpPost.setEntity(entity);

        // set any custom headers on the request            
        for (Map.Entry<String, String> entry : httpHeaders.entrySet()) {
            httpPost.addHeader(entry.getKey(), entry.getValue());
        }

        HttpResponse response = httpClient.execute(httpPost);
        StatusLine statusLine = response.getStatusLine();
        HttpEntity responseEntity = response.getEntity();
        String markup = EntityUtils.toString(responseEntity);

        pResult = new RCoreResultImpl(response.getAllHeaders());
        pResult.parseMarkup(markup, API, statusLine.getStatusCode(), statusLine.getReasonPhrase());

    } catch (UnsupportedEncodingException ueex) {
        log.warn("ProjectWorkspaceUploadCall: unsupported encoding exception.", ueex);
    } catch (IOException ioex) {
        log.warn("ProjectWorkspaceUploadCall: io exception.", ioex);
    }

    return pResult;
}

From source file:cn.vlabs.duckling.vwb.service.ddl.RestClient.java

private HttpEntity buildMultiPartForm(String dataFieldName, String filename, InputStream stream,
        String... params) {/*  ww w.j av  a2s.co m*/
    MultipartEntityBuilder builder = MultipartEntityBuilder.create()
            .setMode(HttpMultipartMode.BROWSER_COMPATIBLE)
            .addBinaryBody(dataFieldName, stream, ContentType.DEFAULT_BINARY, filename);

    if (params != null) {
        for (int i = 0; i < params.length / 2; i++) {
            StringBody contentBody = new StringBody(params[i * 2 + 1], DEFAULT_CONTENT_TYPE);
            builder.addPart(params[i * 2], contentBody);
        }
    }

    HttpEntity reqEntity = builder.setCharset(DEFAULT_CHARSET).build();
    return reqEntity;
}