Search in sources :

Example 6 with FileBody

use of org.apache.http.entity.mime.content.FileBody in project tmdm-studio-se by Talend.

the class HttpClientUtil method createUploadFileToServerRequest.

private static HttpUriRequest createUploadFileToServerRequest(String URL, String userName, final String fileName) {
    HttpPost request = new HttpPost(URL);
    String path = fileName;
    if (URL.indexOf("deletefile") == -1) {
        // $NON-NLS-1$
        if (URL.indexOf("deployjob") != -1) {
            // $NON-NLS-1$
            // $NON-NLS-1$
            path = URL.substring(URL.indexOf("=") + 1);
        }
        MultipartEntity entity = new MultipartEntity();
        entity.addPart(path, new FileBody(new File(fileName)));
        request.setEntity(entity);
    }
    addStudioToken(request, userName);
    return request;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) FileBody(org.apache.http.entity.mime.content.FileBody) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) File(java.io.File)

Example 7 with FileBody

use of org.apache.http.entity.mime.content.FileBody in project liferay-ide by liferay.

the class ServerManagerConnection method updateApplication.

public Object updateApplication(String appName, String absolutePath, IProgressMonitor monitor) throws APIException {
    try {
        final File file = new File(absolutePath);
        final FileBody fileBody = new FileBody(file);
        final MultipartEntity entity = new MultipartEntity();
        entity.addPart(file.getName(), fileBody);
        final HttpPut httpPut = new HttpPut();
        httpPut.setEntity(entity);
        Object response = httpJSONAPI(httpPut, getUpdateURI(appName));
        if (response instanceof JSONObject) {
            JSONObject json = (JSONObject) response;
            if (isSuccess(json)) {
                // $NON-NLS-1$
                System.out.println("updateApplication: success.\n\n");
            } else {
                if (isError(json)) {
                    // $NON-NLS-1$
                    return json.getString("error");
                } else {
                    // $NON-NLS-1$
                    return "updateApplication error " + getDeployURI(appName);
                }
            }
        }
        httpPut.releaseConnection();
    } catch (Exception e) {
        e.printStackTrace();
        return e.getMessage();
    }
    return null;
}
Also used : FileBody(org.apache.http.entity.mime.content.FileBody) JSONObject(org.json.JSONObject) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) JSONObject(org.json.JSONObject) File(java.io.File) HttpPut(org.apache.http.client.methods.HttpPut) APIException(com.liferay.ide.core.remote.APIException) JSONException(org.json.JSONException)

Example 8 with FileBody

use of org.apache.http.entity.mime.content.FileBody in project weixin-boot by guhanjie.

the class MediaKit method postMedia.

public static String postMedia(String path, String type) {
    LOGGER.debug("starting to post media: path[{}] type[{}]...", path, type);
    final WeixinMedia wm = new WeixinMedia();
    try {
        String url = WeixinConstants.API_POST_MEDIA;
        url = url.replace("TYPE", type);
        FileBody fb = new FileBody(new File(path));
        HttpEntity entity = MultipartEntityBuilder.create().addPart("media", fb).build();
        WeixinHttpUtil.sendPost(url, entity, new WeixinHttpCallback() {

            @Override
            public void process(String json) {
                WeixinMedia t = JSONObject.parseObject(json, WeixinMedia.class);
                if (t != null && t.getMedia_id() != null) {
                    wm.setMedia_id(t.getMedia_id());
                    LOGGER.info("Success to post media:[{}].", t.getMedia_id());
                } else {
                    LOGGER.error("Failed to post media.");
                }
            }
        });
    } catch (Exception e) {
        LOGGER.error("error post media: type[{}], path[{}]", type, path);
    }
    return wm.getMedia_id();
}
Also used : WeixinMedia(com.guhanjie.weixin.model.WeixinMedia) FileBody(org.apache.http.entity.mime.content.FileBody) HttpEntity(org.apache.http.HttpEntity) File(java.io.File) WeixinHttpCallback(com.guhanjie.weixin.WeixinHttpUtil.WeixinHttpCallback)

Example 9 with FileBody

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

the class INaturalistService method request.

private JSONArray request(String url, String method, ArrayList<NameValuePair> params, JSONObject jsonContent, boolean authenticated, boolean useJWTToken, boolean allowAnonymousJWTToken) throws AuthenticationException {
    DefaultHttpClient client = new DefaultHttpClient();
    // Handle redirects (301/302) for all HTTP methods (including POST)
    client.setRedirectHandler(new DefaultRedirectHandler() {

        @Override
        public boolean isRedirectRequested(HttpResponse response, HttpContext context) {
            boolean isRedirect = super.isRedirectRequested(response, context);
            if (!isRedirect) {
                int responseCode = response.getStatusLine().getStatusCode();
                if (responseCode == 301 || responseCode == 302) {
                    return true;
                }
            }
            return isRedirect;
        }
    });
    client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, getUserAgent(mApp));
    // Log.d(TAG, String.format("%s (%b - %s): %s", method, authenticated,
    // authenticated ? mCredentials : "<null>",
    // url));
    HttpRequestBase request;
    Log.d(TAG, String.format("URL: %s - %s (%s)", method, url, (params != null ? params.toString() : "null")));
    if (method.equalsIgnoreCase("post")) {
        request = new HttpPost(url);
    } else if (method.equalsIgnoreCase("delete")) {
        request = new HttpDelete(url);
    } else if (method.equalsIgnoreCase("put")) {
        request = new HttpPut(url);
    } else {
        request = new HttpGet(url);
    }
    // POST params
    if (jsonContent != null) {
        // JSON body content
        request.setHeader("Content-type", "application/json");
        StringEntity entity = null;
        try {
            entity = new StringEntity(jsonContent.toString(), HTTP.UTF_8);
        } catch (UnsupportedEncodingException exc) {
            exc.printStackTrace();
        }
        if (method.equalsIgnoreCase("put")) {
            ((HttpPut) request).setEntity(entity);
        } else {
            ((HttpPost) request).setEntity(entity);
        }
    } else if (params != null) {
        // "Standard" multipart encoding
        Charset utf8Charset = Charset.forName("UTF-8");
        MultipartEntity entity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
        for (int i = 0; i < params.size(); i++) {
            if (params.get(i).getName().equalsIgnoreCase("image") || params.get(i).getName().equalsIgnoreCase("file") || params.get(i).getName().equalsIgnoreCase("user[icon]")) {
                // If the key equals to "image", we use FileBody to transfer the data
                String value = params.get(i).getValue();
                if (value != null)
                    entity.addPart(params.get(i).getName(), new FileBody(new File(value)));
            } else {
                // Normal string data
                try {
                    entity.addPart(params.get(i).getName(), new StringBody(params.get(i).getValue(), utf8Charset));
                } catch (UnsupportedEncodingException e) {
                    Log.e(TAG, "failed to add " + params.get(i).getName() + " to entity for a " + method + " request: " + e);
                }
            }
        }
        if (method.equalsIgnoreCase("put")) {
            ((HttpPut) request).setEntity(entity);
        } else {
            ((HttpPost) request).setEntity(entity);
        }
    }
    if (url.startsWith(API_HOST) && (mCredentials != null)) {
        // For the node API, if we're logged in, *always* use JWT authentication
        authenticated = true;
        useJWTToken = true;
    }
    if (authenticated) {
        if (useJWTToken && allowAnonymousJWTToken && (mCredentials == null)) {
            // User not logged in, but allow using anonymous JWT
            request.setHeader("Authorization", getAnonymousJWTToken());
        } else {
            ensureCredentials();
            if (useJWTToken) {
                // Use JSON Web Token for this request
                request.setHeader("Authorization", getJWTToken());
            } else if (mLoginType == LoginType.PASSWORD) {
                // Old-style password authentication
                request.setHeader("Authorization", "Basic " + mCredentials);
            } else {
                // OAuth2 token (Facebook/G+/etc)
                request.setHeader("Authorization", "Bearer " + mCredentials);
            }
        }
    }
    try {
        mResponseErrors = null;
        HttpResponse response = client.execute(request);
        HttpEntity entity = response.getEntity();
        String content = entity != null ? EntityUtils.toString(entity) : null;
        Log.d(TAG, String.format("RESP: %s", content));
        JSONArray json = null;
        mLastStatusCode = response.getStatusLine().getStatusCode();
        switch(response.getStatusLine().getStatusCode()) {
            // switch (response.getStatusCode()) {
            case HttpStatus.SC_UNPROCESSABLE_ENTITY:
                // Validation error - still need to return response
                Log.e(TAG, response.getStatusLine().toString());
            case HttpStatus.SC_OK:
                try {
                    json = new JSONArray(content);
                } catch (JSONException e) {
                    Log.d(TAG, "Failed to create JSONArray, JSONException: " + e.toString());
                    try {
                        JSONObject jo = new JSONObject(content);
                        json = new JSONArray();
                        json.put(jo);
                    } catch (JSONException e2) {
                        Log.d(TAG, "Failed to create JSONObject, JSONException: " + e2.toString());
                    }
                }
                mResponseHeaders = response.getAllHeaders();
                try {
                    if ((json != null) && (json.length() > 0)) {
                        JSONObject result = json.getJSONObject(0);
                        if (result.has("errors")) {
                            // Error response
                            Log.e(TAG, "Got an error response: " + result.get("errors").toString());
                            mResponseErrors = result.getJSONArray("errors");
                            return null;
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if ((content != null) && (content.length() == 0)) {
                    // In case it's just non content (but OK HTTP status code) - so there's no error
                    json = new JSONArray();
                }
                return json;
            case HttpStatus.SC_UNAUTHORIZED:
                throw new AuthenticationException();
            case HttpStatus.SC_GONE:
                Log.e(TAG, "GONE: " + response.getStatusLine().toString());
            // or post them as new observations
            default:
                Log.e(TAG, response.getStatusLine().toString());
        }
    } catch (IOException e) {
        // request.abort();
        Log.w(TAG, "Error for URL " + url, e);
    }
    return null;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) HttpRequestBase(org.apache.http.client.methods.HttpRequestBase) HttpDelete(org.apache.http.client.methods.HttpDelete) FileBody(org.apache.http.entity.mime.content.FileBody) HttpEntity(org.apache.http.HttpEntity) HttpGet(org.apache.http.client.methods.HttpGet) HttpContext(org.apache.http.protocol.HttpContext) JSONArray(org.json.JSONArray) HttpResponse(org.apache.http.HttpResponse) UnsupportedEncodingException(java.io.UnsupportedEncodingException) Charset(java.nio.charset.Charset) JSONException(org.json.JSONException) IOException(java.io.IOException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpPut(org.apache.http.client.methods.HttpPut) StringEntity(org.apache.http.entity.StringEntity) DefaultRedirectHandler(org.apache.http.impl.client.DefaultRedirectHandler) JSONObject(org.json.JSONObject) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) StringBody(org.apache.http.entity.mime.content.StringBody) File(java.io.File)

Example 10 with FileBody

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

the class AggregateUtils method uploadFilesToServer.

public static final boolean uploadFilesToServer(ServerConnectionInfo serverInfo, URI u, String distinguishedFileTagName, File file, List<File> files, DocumentDescription description, SubmissionResponseAction action, TerminationFuture terminationFuture, FormStatus formToTransfer) {
    boolean allSuccessful = true;
    formToTransfer.setStatusString("Preparing for upload of " + description.getDocumentDescriptionType() + " with " + files.size() + " media attachments", true);
    EventBus.publish(new FormStatusEvent(formToTransfer));
    // handles case where there are no media files
    boolean first = true;
    int lastJ = 0;
    int j = 0;
    while (j < files.size() || first) {
        lastJ = j;
        first = false;
        if (terminationFuture.isCancelled()) {
            formToTransfer.setStatusString("Aborting upload of " + description.getDocumentDescriptionType() + " with " + files.size() + " media attachments", true);
            EventBus.publish(new FormStatusEvent(formToTransfer));
            return false;
        }
        HttpPost httppost = WebUtils.createOpenRosaHttpPost(u);
        long byteCount = 0L;
        // mime post
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        // add the submission file first...
        FileBody fb = new FileBody(file, ContentType.TEXT_XML);
        builder.addPart(distinguishedFileTagName, fb);
        log.info("added " + distinguishedFileTagName + ": " + file.getName());
        byteCount += file.length();
        for (; j < files.size(); j++) {
            File f = files.get(j);
            log.info("Trying file {}", f);
            String fileName = f.getName();
            int idx = fileName.lastIndexOf(".");
            String extension = "";
            if (idx != -1) {
                extension = fileName.substring(idx + 1);
            }
            // we only need to deal with the content type determination...
            if (extension.equals("xml")) {
                fb = new FileBody(f, ContentType.TEXT_XML);
                builder.addPart(f.getName(), fb);
                byteCount += f.length();
                log.info("added xml file " + f.getName());
            } else if (extension.equals("jpg")) {
                fb = new FileBody(f, ContentType.create("image/jpeg"));
                builder.addPart(f.getName(), fb);
                byteCount += f.length();
                log.info("added image file " + f.getName());
            } else if (extension.equals("3gpp")) {
                fb = new FileBody(f, ContentType.create("audio/3gpp"));
                builder.addPart(f.getName(), fb);
                byteCount += f.length();
                log.info("added audio file " + f.getName());
            } else if (extension.equals("3gp")) {
                fb = new FileBody(f, ContentType.create("video/3gpp"));
                builder.addPart(f.getName(), fb);
                byteCount += f.length();
                log.info("added video file " + f.getName());
            } else if (extension.equals("mp4")) {
                fb = new FileBody(f, ContentType.create("video/mp4"));
                builder.addPart(f.getName(), fb);
                byteCount += f.length();
                log.info("added video file " + f.getName());
            } else if (extension.equals("csv")) {
                fb = new FileBody(f, ContentType.create("text/csv"));
                builder.addPart(f.getName(), fb);
                byteCount += f.length();
                log.info("added csv file " + f.getName());
            } else if (extension.equals("xls")) {
                fb = new FileBody(f, ContentType.create("application/vnd.ms-excel"));
                builder.addPart(f.getName(), fb);
                byteCount += f.length();
                log.info("added xls file " + f.getName());
            } else {
                fb = new FileBody(f, ContentType.create("application/octet-stream"));
                builder.addPart(f.getName(), fb);
                byteCount += f.length();
                log.warn("added unrecognized file (application/octet-stream)");
            }
            // we've added at least one attachment to the request...
            if (j + 1 < files.size()) {
                if ((j - lastJ + 1) > 100 || byteCount + files.get(j + 1).length() > 10000000L) {
                    // more than 100 attachments or the next file would exceed the 10MB threshold...
                    log.info("Extremely long post is being split into multiple posts");
                    try {
                        StringBody sb = new StringBody("yes", ContentType.DEFAULT_TEXT.withCharset(Charset.forName("UTF-8")));
                        builder.addPart("*isIncomplete*", sb);
                    } catch (Exception e) {
                        log.error("impossible condition", e);
                        throw new IllegalStateException("never happens");
                    }
                    // advance over the last attachment added...
                    ++j;
                    break;
                }
            }
        }
        httppost.setEntity(builder.build());
        int[] validStatusList = { 201 };
        try {
            if (j != files.size()) {
                formToTransfer.setStatusString("Uploading " + description.getDocumentDescriptionType() + " and media files " + (lastJ + 1) + " through " + (j + 1) + " of " + files.size() + " media attachments", true);
            } else if (j == 0) {
                formToTransfer.setStatusString("Uploading " + description.getDocumentDescriptionType() + " with no media attachments", true);
            } else {
                formToTransfer.setStatusString("Uploading " + description.getDocumentDescriptionType() + " and " + (j - lastJ) + ((lastJ != 0) ? " remaining" : "") + " media attachments", true);
            }
            EventBus.publish(new FormStatusEvent(formToTransfer));
            httpRetrieveXmlDocument(httppost, validStatusList, serverInfo, false, description, action);
        } catch (XmlDocumentFetchException e) {
            allSuccessful = false;
            log.error("upload failed", e);
            formToTransfer.setStatusString("UPLOAD FAILED: " + e.getMessage(), false);
            EventBus.publish(new FormStatusEvent(formToTransfer));
            if (description.isCancelled())
                return false;
        }
    }
    return allSuccessful;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) FileBody(org.apache.http.entity.mime.content.FileBody) FormStatusEvent(org.opendatakit.briefcase.model.FormStatusEvent) ClientProtocolException(org.apache.http.client.ClientProtocolException) URISyntaxException(java.net.URISyntaxException) TransmissionException(org.opendatakit.briefcase.model.TransmissionException) MalformedURLException(java.net.MalformedURLException) XmlDocumentFetchException(org.opendatakit.briefcase.model.XmlDocumentFetchException) IOException(java.io.IOException) MetadataUpdateException(org.opendatakit.briefcase.model.MetadataUpdateException) UnknownHostException(java.net.UnknownHostException) XmlDocumentFetchException(org.opendatakit.briefcase.model.XmlDocumentFetchException) StringBody(org.apache.http.entity.mime.content.StringBody) File(java.io.File)

Aggregations

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