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: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 {/*  ww w. j av  a 2s  .c om*/
        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;//w  w w .j a  v  a  2s.  c om

    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);//  w  w w .ja  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:com.neighbor.ex.tong.network.UploadFileAndMessage.java

@Override
protected Void doInBackground(Void... voids) {
    try {//w  ww  .  j  a  v  a  2s.co m

        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.addTextBody("message", URLEncoder.encode(message, "UTF-8"),
                ContentType.create("Multipart/related", "UTF-8"));
        builder.addPart("image", new FileBody(new File(path)));

        InputStream inputStream = null;
        HttpClient httpClient = AndroidHttpClient.newInstance("Android");

        String carNo = prefs.getString(CONST.ACCOUNT_LICENSE, "");
        String encodeCarNo = "";

        if (false == carNo.equals("")) {
            encodeCarNo = URLEncoder.encode(carNo, "UTF-8");
        }
        HttpPost httpPost = new HttpPost(UPLAOD_URL + encodeCarNo);
        httpPost.setEntity(builder.build());
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        inputStream = httpEntity.getContent();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
        StringBuilder stringBuilder = new StringBuilder();
        String line = null;

        while ((line = bufferedReader.readLine()) != null) {
            stringBuilder.append(line + "\n");
        }
        inputStream.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.codota.uploader.Uploader.java

private void uploadFile(File file, String uploadUrl) throws IOException {
    HttpPut putRequest = new HttpPut(uploadUrl);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
    builder.addPart("code", new FileBody(file));
    final HttpEntity entity = builder.build();
    putRequest.setEntity(entity);// w  w  w  . j  a  va  2 s.  c o m

    putRequest.setHeader("enctype", "multipart/form-data");
    putRequest.setHeader("authorization", "bearer " + token);
    httpClient.execute(putRequest, new UploadResponseHandler());
}

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

/**
 * Put.//from w ww . j  av 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//from   w ww . j  a va2  s . c  o m
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:com.onaio.steps.helper.UploadFileTask.java

@Override
protected Boolean doInBackground(File... files) {
    if (!TextUtils.isEmpty(KeyValueStoreFactory.instance(activity).getString(ENDPOINT_URL))) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost httpPost = new HttpPost(KeyValueStoreFactory.instance(activity).getString(ENDPOINT_URL));
        try {// www .ja va 2 s. co  m
            MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
                    Charset.forName("UTF-8"));
            multipartEntity.addPart("file", new FileBody(files[0]));
            httpPost.setEntity(multipartEntity);
            httpClient.execute(httpPost);
            new CustomNotification().notify(activity, R.string.export_complete,
                    R.string.export_complete_message);
            return true;
        } catch (IOException e) {
            new Logger().log(e, "Export failed.");
            new CustomNotification().notify(activity, R.string.error_title, R.string.export_failed);
        }
    } else {
        new CustomNotification().notify(activity, R.string.error_title, R.string.export_failed);
    }

    return false;
}

From source file:com.ls.http.base.handler.MultipartRequestHandler.java

public MultipartRequestHandler() {
    this.entity = MultipartEntityBuilder.create();
    entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
}

From source file:org.semantictools.jsonld.impl.AppspotContextPublisher.java

@Override
public void publish(LdAsset asset) throws LdPublishException {

    String uri = asset.getURI();//  w ww . j a va 2 s  .co  m

    HttpClient client = new DefaultHttpClient();
    HttpPost post = new HttpPost(SERVLET_URL);
    post.setHeader("CONTENT-TYPE", "multipart/form-data; boundary=xxxBOUNDARYxxx");
    MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, "xxxBOUNDARYxxx",
            Charset.forName("UTF-8"));

    try {

        String content = asset.loadContent();

        entity.addPart(URI, new StringBody(uri));
        entity.addPart(FILE_UPLOAD, new StringBody(content));
        post.setEntity(entity);

        logger.debug("uploading... " + uri);

        HttpResponse response = client.execute(post);
        int status = response.getStatusLine().getStatusCode();

        client.getConnectionManager().shutdown();
        if (status != HttpURLConnection.HTTP_OK) {
            throw new LdPublishException(uri, null);
        }

    } catch (Exception e) {
        throw new LdPublishException(uri, e);
    }

}