Search in sources :

Example 1 with FileBody

use of org.apache.http.entity.mime.content.FileBody in project UltimateAndroid by cymcsg.

the class HttpUtils method uploadFilesMPE.

/**
     * Update Files via Multipart
     *
     * @param url
     * @param paramsList
     * @param fileParams
     * @param file
     * @param files
     * @return status
     * @deprecated
     */
public static String uploadFilesMPE(String url, List<NameValuePair> paramsList, String fileParams, File file, File... files) {
    String result = "";
    try {
        DefaultHttpClient mHttpClient;
        HttpParams params = new BasicHttpParams();
        params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        params.setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
        params.setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);
        mHttpClient = new DefaultHttpClient(params);
        HttpPost httpPost = new HttpPost(url);
        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        if (BasicUtils.judgeNotNull(paramsList)) {
            for (NameValuePair nameValuePair : paramsList) {
                multipartEntity.addPart(nameValuePair.getName(), new StringBody(nameValuePair.getValue()));
            }
        }
        multipartEntity.addPart(fileParams, new FileBody(file));
        for (File f : files) {
            multipartEntity.addPart(fileParams, new FileBody(f));
        }
        httpPost.setEntity(multipartEntity);
        HttpResponse httpResp = mHttpClient.execute(httpPost);
        // 判断是够请求成功
        if (httpResp.getStatusLine().getStatusCode() == 200) {
            // 获取返回的数据
            result = EntityUtils.toString(httpResp.getEntity(), "UTF-8");
            Logs.d("HttpPost success :");
            Logs.d(result);
        } else {
            Logs.d("HttpPost failed" + "    " + httpResp.getStatusLine().getStatusCode() + "   " + EntityUtils.toString(httpResp.getEntity(), "UTF-8"));
            result = "HttpPost failed";
        }
    } catch (ConnectTimeoutException e) {
        result = "ConnectTimeoutException";
        Logs.e("HttpPost overtime:  " + "");
    } catch (Exception e) {
        e.printStackTrace();
        Logs.e(e, "");
        result = "Exception";
    }
    return result;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) FileBody(org.apache.http.entity.mime.content.FileBody) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) StringBody(org.apache.http.entity.mime.content.StringBody) File(java.io.File) ConnectTimeoutException(org.apache.http.conn.ConnectTimeoutException)

Example 2 with FileBody

use of org.apache.http.entity.mime.content.FileBody in project screenbird by adamhub.

the class FileUtil method postFile.

/**
     * Uploads a file via a POST request to a URL.
     * @param fileLocation  path to the file that will be uploaded
     * @param title         title of the video
     * @param slug          slug of the video 
     * @param description   description of the video
     * @param video_type    format of the video (mp4, mpg, avi, etc.)
     * @param checksum      checksum of the file that will be uploaded
     * @param is_public     publicity settings of the file
     * @param pbUpload      progress bar for the upload
     * @param fileSize      the length, in bytes, of the file to be uploaded
     * @param csrf_token    csrf token for the POST request
     * @param user_id       Screenbird user id of the uploader
     * @param channel_id    Screenbird channel id to where the video will be uploaded to
     * @param an_tok        anonymous token identifier if the uploader is not logged in to Screenbird
     * @param listener      listener for the upload
     * @param upload_url    URL where the POST request will be sent to.
     * @return
     * @throws IOException 
     */
public static String[] postFile(String fileLocation, String title, String slug, String description, String video_type, String checksum, Boolean is_public, final JProgressBar pbUpload, long fileSize, String csrf_token, String user_id, String channel_id, String an_tok, ProgressBarUploadProgressListener listener, String upload_url) throws IOException {
    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    HttpPost httppost = new HttpPost(upload_url);
    File file = new File(fileLocation);
    ProgressMultiPartEntity mpEntity = new ProgressMultiPartEntity(listener);
    ContentBody cbFile = new FileBody(file, "video/quicktime");
    mpEntity.addPart("videoupload", cbFile);
    ContentBody cbToken = new StringBody(title);
    mpEntity.addPart("csrfmiddlewaretoken", cbToken);
    ContentBody cbUser_id = new StringBody(user_id);
    mpEntity.addPart("user_id", cbUser_id);
    ContentBody cbChannel_id = new StringBody(channel_id);
    mpEntity.addPart("channel_id", cbChannel_id);
    ContentBody cbAnonym_id = new StringBody(an_tok);
    mpEntity.addPart("an_tok", cbAnonym_id);
    ContentBody cbTitle = new StringBody(title);
    mpEntity.addPart("title", cbTitle);
    ContentBody cbSlug = new StringBody(slug);
    mpEntity.addPart("slug", cbSlug);
    ContentBody cbPublic = new StringBody(is_public ? "1" : "0");
    mpEntity.addPart("is_public", cbPublic);
    ContentBody cbDescription = new StringBody(description);
    mpEntity.addPart("description", cbDescription);
    ContentBody cbChecksum = new StringBody(checksum);
    mpEntity.addPart("checksum", cbChecksum);
    ContentBody cbType = new StringBody(video_type);
    mpEntity.addPart("video_type", cbType);
    httppost.setEntity(mpEntity);
    log("===================================================");
    log("executing request " + httppost.getRequestLine());
    log("===================================================");
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();
    String[] result = new String[2];
    String status = response.getStatusLine().toString();
    result[0] = (status.indexOf("200") >= 0) ? "200" : status;
    log("===================================================");
    log("response " + response.toString());
    log("===================================================");
    if (resEntity != null) {
        result[1] = EntityUtils.toString(resEntity);
        EntityUtils.consume(resEntity);
    }
    httpclient.getConnectionManager().shutdown();
    return result;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) ContentBody(org.apache.http.entity.mime.content.ContentBody) FileBody(org.apache.http.entity.mime.content.FileBody) HttpEntity(org.apache.http.HttpEntity) StringBody(org.apache.http.entity.mime.content.StringBody) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) ProgressMultiPartEntity(com.bixly.pastevid.screencap.components.progressbar.ProgressMultiPartEntity) HttpResponse(org.apache.http.HttpResponse) File(java.io.File) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient)

Example 3 with FileBody

use of org.apache.http.entity.mime.content.FileBody in project android-instagram by markchang.

the class TakePictureActivity method doUpload.

// fixme: this doesn't need to be a Map return
public Map<String, String> doUpload() {
    Log.i(TAG, "Upload");
    Long timeInMilliseconds = System.currentTimeMillis() / 1000;
    String timeInSeconds = timeInMilliseconds.toString();
    MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
    Map returnMap = new HashMap<String, String>();
    // check for cookies
    if (httpClient.getCookieStore() == null) {
        returnMap.put("result", "Not logged in");
        return returnMap;
    }
    try {
        // create multipart data
        File imageFile = new File(processedImageUri.getPath());
        FileBody partFile = new FileBody(imageFile);
        StringBody partTime = new StringBody(timeInSeconds);
        multipartEntity.addPart("photo", partFile);
        multipartEntity.addPart("device_timestamp", partTime);
    } catch (Exception e) {
        Log.e(TAG, "Error creating mulitpart form: " + e.toString());
        returnMap.put("result", "Error creating mulitpart form: " + e.toString());
        return returnMap;
    }
    // upload
    try {
        HttpPost httpPost = new HttpPost(Utils.UPLOAD_URL);
        httpPost.setEntity(multipartEntity);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        Log.i(TAG, "Upload status: " + httpResponse.getStatusLine());
        // test result code
        if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            Log.e(TAG, "Login HTTP status fail: " + httpResponse.getStatusLine().getStatusCode());
            returnMap.put("result", "HTTP status error: " + httpResponse.getStatusLine().getStatusCode());
            return returnMap;
        }
        /*
            {"status": "ok"}
            */
        if (httpEntity != null) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(httpEntity.getContent(), "UTF-8"));
            String json = reader.readLine();
            JSONTokener jsonTokener = new JSONTokener(json);
            JSONObject jsonObject = new JSONObject(jsonTokener);
            Log.i(TAG, "JSON: " + jsonObject.toString());
            String loginStatus = jsonObject.getString("status");
            if (!loginStatus.equals("ok")) {
                Log.e(TAG, "JSON status not ok: " + jsonObject.getString("status"));
                returnMap.put("result", "JSON status not ok: " + jsonObject.getString("status"));
                return returnMap;
            }
        }
    } catch (Exception e) {
        Log.e(TAG, "HttpPost exception: " + e.toString());
        returnMap.put("result", "HttpPost exception: " + e.toString());
        return returnMap;
    }
    // configure / comment
    try {
        HttpPost httpPost = new HttpPost(Utils.CONFIGURE_URL);
        String partComment = txtCaption.getText().toString();
        List<NameValuePair> postParams = new ArrayList<NameValuePair>();
        postParams.add(new BasicNameValuePair("device_timestamp", timeInSeconds));
        postParams.add(new BasicNameValuePair("caption", partComment));
        httpPost.setEntity(new UrlEncodedFormEntity(postParams, HTTP.UTF_8));
        HttpResponse httpResponse = httpClient.execute(httpPost);
        HttpEntity httpEntity = httpResponse.getEntity();
        // test result code
        if (httpResponse.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
            Log.e(TAG, "Upload comment fail: " + httpResponse.getStatusLine().getStatusCode());
            returnMap.put("result", "Upload comment fail: " + httpResponse.getStatusLine().getStatusCode());
            return returnMap;
        }
        returnMap.put("result", "ok");
        return returnMap;
    } catch (Exception e) {
        Log.e(TAG, "HttpPost comment error: " + e.toString());
        returnMap.put("result", "HttpPost comment error: " + e.toString());
        return returnMap;
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) NameValuePair(org.apache.http.NameValuePair) FileBody(org.apache.http.entity.mime.content.FileBody) HttpEntity(org.apache.http.HttpEntity) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) HttpResponse(org.apache.http.HttpResponse) UrlEncodedFormEntity(org.apache.http.client.entity.UrlEncodedFormEntity) JSONTokener(org.json.JSONTokener) JSONObject(org.json.JSONObject) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) StringBody(org.apache.http.entity.mime.content.StringBody) BasicNameValuePair(org.apache.http.message.BasicNameValuePair) HashMap(java.util.HashMap) Map(java.util.Map)

Example 4 with FileBody

use of org.apache.http.entity.mime.content.FileBody in project streamsx.topology by IBMStreams.

the class BuildServiceRemoteRESTWrapper method doUploadBuildArchivePost.

private JsonObject doUploadBuildArchivePost(CloseableHttpClient httpclient, String apiKey, File archive, String buildName) throws ClientProtocolException, IOException {
    String newBuildURL = getBuildsURL() + "?build_name=" + URLEncoder.encode(buildName, StandardCharsets.UTF_8.name());
    HttpPost httppost = new HttpPost(newBuildURL);
    httppost.addHeader("accept", ContentType.APPLICATION_JSON.getMimeType());
    httppost.addHeader("Authorization", apiKey);
    FileBody archiveBody = new FileBody(archive, ContentType.create("application/zip"));
    HttpEntity reqEntity = MultipartEntityBuilder.create().addPart(archive.getName(), archiveBody).build();
    httppost.setEntity(reqEntity);
    JsonObject jso = RestUtils.getGsonResponse(httpclient, httppost);
    return jso;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) FileBody(org.apache.http.entity.mime.content.FileBody) HttpEntity(org.apache.http.HttpEntity) JsonObject(com.google.gson.JsonObject)

Example 5 with FileBody

use of org.apache.http.entity.mime.content.FileBody in project sling by apache.

the class WebconsoleClient method installBundle.

/** Install a bundle using the Felix webconsole HTTP interface, with a specific start level */
public void installBundle(File f, boolean startBundle, int startLevel) throws Exception {
    // Setup request for Felix Webconsole bundle install
    final MultipartEntity entity = new MultipartEntity();
    entity.addPart("action", new StringBody("install"));
    if (startBundle) {
        entity.addPart("bundlestart", new StringBody("true"));
    }
    entity.addPart("bundlefile", new FileBody(f));
    if (startLevel > 0) {
        entity.addPart("bundlestartlevel", new StringBody(String.valueOf(startLevel)));
        log.info("Installing bundle {} at start level {}", f.getName(), startLevel);
    } else {
        log.info("Installing bundle {} at default start level", f.getName());
    }
    // Console returns a 302 on success (and in a POST this
    // is not handled automatically as per HTTP spec)
    executor.execute(builder.buildPostRequest(CONSOLE_BUNDLES_PATH).withCredentials(username, password).withEntity(entity)).assertStatus(302);
}
Also used : FileBody(org.apache.http.entity.mime.content.FileBody) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) StringBody(org.apache.http.entity.mime.content.StringBody)

Aggregations

FileBody (org.apache.http.entity.mime.content.FileBody)60 HttpPost (org.apache.http.client.methods.HttpPost)45 File (java.io.File)40 MultipartEntity (org.apache.http.entity.mime.MultipartEntity)37 HttpResponse (org.apache.http.HttpResponse)30 StringBody (org.apache.http.entity.mime.content.StringBody)30 HttpEntity (org.apache.http.HttpEntity)17 Test (org.junit.Test)17 IOException (java.io.IOException)16 MultipartEntityBuilder (org.apache.http.entity.mime.MultipartEntityBuilder)15 TestHttpClient (io.undertow.testutils.TestHttpClient)11 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)7 CloseableHttpClient (org.apache.http.impl.client.CloseableHttpClient)6 JsonObject (com.google.gson.JsonObject)5 HttpClient (org.apache.http.client.HttpClient)5 CloseableHttpResponse (org.apache.http.client.methods.CloseableHttpResponse)5 JSONObject (org.json.JSONObject)5 BlockingHandler (io.undertow.server.handlers.BlockingHandler)4 BufferedReader (java.io.BufferedReader)4 FileInputStream (java.io.FileInputStream)3