Search in sources :

Example 1 with FileBody

use of org.apache.hc.client5.http.entity.mime.FileBody in project mercury by yellow013.

the class ClientMultipartFormPost method main.

public static void main(final String[] args) throws Exception {
    if (args.length != 1) {
        System.out.println("File path not given");
        System.exit(1);
    }
    try (final CloseableHttpClient httpclient = HttpClients.createDefault()) {
        final HttpPost httppost = new HttpPost("http://localhost:8080" + "/servlets-examples/servlet/RequestInfoExample");
        final FileBody bin = new FileBody(new File(args[0]));
        final StringBody comment = new StringBody("A binary file of some kind", ContentType.TEXT_PLAIN);
        final HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bin", bin).addPart("comment", comment).build();
        httppost.setEntity(reqEntity);
        System.out.println("executing request " + httppost);
        try (final CloseableHttpResponse response = httpclient.execute(httppost)) {
            System.out.println("----------------------------------------");
            System.out.println(response);
            final HttpEntity resEntity = response.getEntity();
            if (resEntity != null) {
                System.out.println("Response content length: " + resEntity.getContentLength());
            }
            EntityUtils.consume(resEntity);
        }
    }
}
Also used : CloseableHttpClient(org.apache.hc.client5.http.impl.classic.CloseableHttpClient) HttpPost(org.apache.hc.client5.http.classic.methods.HttpPost) FileBody(org.apache.hc.client5.http.entity.mime.FileBody) HttpEntity(org.apache.hc.core5.http.HttpEntity) StringBody(org.apache.hc.client5.http.entity.mime.StringBody) CloseableHttpResponse(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse) File(java.io.File)

Example 2 with FileBody

use of org.apache.hc.client5.http.entity.mime.FileBody in project alfresco-process-services-project-sdk by OpenPj.

the class IntegrationTestUtils method importApp.

/**
 * This method will import and publish an APS application against an APS
 * instance
 *
 * @param appZipFile is the filename of the app that should be available in the
 *                   target/apps folder of the Integration Test module
 * @param username   is the username of a user that can import new applications
 *                   in APS
 * @param password   is the password of a user that can import new applications
 *                   in APS
 * @param protocol   of the APS instance
 * @param hostname   of the APS instance
 * @param port       of the APS instance
 */
public static void importApp(String appZipFile, String username, String password, String protocol, String hostname, Integer port) {
    Path resourceFourEyesAppZip = Paths.get("target", "apps", appZipFile);
    File file = resourceFourEyesAppZip.toFile();
    try {
        final BasicScheme basicAuth = new BasicScheme();
        basicAuth.initPreemptive(new UsernamePasswordCredentials(username, password.toCharArray()));
        final HttpHost target = new HttpHost(protocol, hostname, port);
        final HttpClientContext localContext = HttpClientContext.create();
        localContext.resetAuthExchange(target, basicAuth);
        try (final CloseableHttpClient httpclient = HttpClients.createDefault()) {
            final String publishAppUrl = protocol + "://" + hostname + ":" + port.toString() + PUBLISH_APP_ENDPOINT;
            final HttpPost httppost = new HttpPost(publishAppUrl);
            final FileBody binaryFile = new FileBody(file);
            final HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("file", binaryFile).build();
            httppost.setEntity(reqEntity);
            System.out.println("Importing app " + httppost);
            try (final CloseableHttpResponse response = httpclient.execute(httppost, localContext)) {
                System.out.println("----------------------------------------");
                System.out.println(response);
                final HttpEntity resEntity = response.getEntity();
                if (resEntity != null) {
                    System.out.println("Response content length: " + resEntity.getContentLength());
                }
                EntityUtils.consume(resEntity);
            }
        }
    } catch (FileNotFoundException e) {
        fail(e.getMessage(), e);
    } catch (IOException e) {
        fail(e.getMessage(), e);
    }
}
Also used : Path(java.nio.file.Path) BasicScheme(org.apache.hc.client5.http.impl.auth.BasicScheme) CloseableHttpClient(org.apache.hc.client5.http.impl.classic.CloseableHttpClient) HttpPost(org.apache.hc.client5.http.classic.methods.HttpPost) FileBody(org.apache.hc.client5.http.entity.mime.FileBody) HttpEntity(org.apache.hc.core5.http.HttpEntity) FileNotFoundException(java.io.FileNotFoundException) HttpClientContext(org.apache.hc.client5.http.protocol.HttpClientContext) IOException(java.io.IOException) UsernamePasswordCredentials(org.apache.hc.client5.http.auth.UsernamePasswordCredentials) HttpHost(org.apache.hc.core5.http.HttpHost) CloseableHttpResponse(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse) File(java.io.File)

Example 3 with FileBody

use of org.apache.hc.client5.http.entity.mime.FileBody in project ajapaik-android-app by Ajapaik.

the class WebOperation method performRequest.

public boolean performRequest(String baseURL, Map<String, String> extraParameters, BasicCookieStore cookieStore) {
    Log.d(TAG, "performRequest()");
    ConnectivityManager cm = (ConnectivityManager) m_context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo info = cm.getActiveNetworkInfo();
    boolean isPost = isPost();
    String url = m_url;
    URI uri;
    if (baseURL != null && !url.contains("://")) {
        if (url.startsWith("/") && baseURL.endsWith("/")) {
            url = baseURL + url.substring(1);
        } else {
            url = baseURL + url;
        }
    }
    if (m_client == null) {
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "new m_client");
        }
        try {
            m_client = HttpClients.custom().setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy()).setDefaultCookieStore(cookieStore).build();
        } catch (Exception e) {
            Log.w(TAG, e.toString());
        }
    }
    if (BuildConfig.DEBUG) {
        Log.d(TAG, "m_client ready");
    }
    m_started = true;
    if (info == null || info.getState() == NetworkInfo.State.DISCONNECTED) {
        onFailure();
        if (BuildConfig.DEBUG) {
            Log.d(TAG, "No network connection");
        }
        return false;
    }
    try {
        uri = URI.create(url);
    } catch (Exception e) {
        Log.w(TAG, "Unable to parse URL (" + url + ")");
        onFailure();
        return false;
    }
    for (int i = 0; i < RETRY_COUNT && !m_cancelled; i++) {
        CloseableHttpResponse response = null;
        HttpUriRequestBase request;
        if (isPost) {
            HttpPost postRequest = new HttpPost(uri);
            request = postRequest;
            if (m_file != null || (extraParameters != null && extraParameters.size() > 0) || (m_parameters != null && m_parameters.size() > 0)) {
                List<NameValuePair> postData = new ArrayList<NameValuePair>(((extraParameters != null) ? extraParameters.size() : 0) + ((m_parameters != null) ? m_parameters.size() : 0));
                if (m_parameters != null) {
                    for (Map.Entry<String, String> entry : m_parameters.entrySet()) {
                        postData.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                    }
                }
                if (extraParameters != null) {
                    for (Map.Entry<String, String> entry : extraParameters.entrySet()) {
                        postData.add(new BasicNameValuePair(entry.getKey(), entry.getValue()));
                    }
                }
                try {
                    StringBuilder strData = new StringBuilder();
                    String separator = "";
                    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
                    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
                    if (m_file != null) {
                        Log.d(TAG, "Adding file to post");
                        for (NameValuePair pair : postData) {
                            StringBody stringBody1 = new StringBody(pair.getValue(), ContentType.MULTIPART_FORM_DATA);
                            builder.addPart(pair.getName(), stringBody1);
                            strData.append(separator);
                            strData.append(pair.toString());
                            separator = "&";
                        }
                        FileBody fileBody = new FileBody(m_file, ContentType.DEFAULT_BINARY);
                        builder.addPart("original", fileBody);
                        HttpEntity entity = builder.build();
                        postRequest.setEntity(entity);
                    } else {
                        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postData);
                        postRequest.setEntity(entity);
                        for (NameValuePair pair : postData) {
                            strData.append(separator);
                            strData.append(pair.toString());
                            separator = "&";
                        }
                    }
                    if (BuildConfig.DEBUG) {
                        Log.d(TAG, strData.toString());
                    }
                } catch (Exception e) {
                    Log.d(TAG, "UTF8 is not supported");
                }
            }
        } else if ((extraParameters != null && extraParameters.size() > 0) || (m_parameters != null && m_parameters.size() > 0)) {
            Uri.Builder uriBuilder = Uri.parse(m_url).buildUpon();
            if (m_parameters != null) {
                for (Map.Entry<String, String> entry : m_parameters.entrySet()) {
                    uriBuilder.appendQueryParameter(entry.getKey(), entry.getValue());
                }
            }
            if (extraParameters != null) {
                for (Map.Entry<String, String> entry : extraParameters.entrySet()) {
                    uriBuilder.appendQueryParameter(entry.getKey(), entry.getValue());
                }
            }
            request = new HttpGet(URI.create(uriBuilder.build().toString()));
        } else {
            request = new HttpGet(uri);
        }
        request.setHeader("Accept-Encoding", CONTENT_ENCODING_GZIP);
        try {
            String encoding = null;
            HttpEntity entity;
            if (BuildConfig.DEBUG) {
                Log.e(TAG, "Retry count:" + i);
                Log.e(TAG, ((isPost) ? "POST: " : "GET: ") + request.toString());
                Log.e(TAG, "Cookies before: " + cookieStore.getCookies().toString());
            }
            response = m_client.execute(request);
            if ((entity = response.getEntity()) != null) {
                encoding = entity.getContentEncoding();
            }
            try {
                onResponse(response.getCode(), (encoding != null && CONTENT_ENCODING_GZIP.equals(encoding)) ? new GZIPInputStream(entity.getContent()) : entity.getContent());
                Log.e(TAG, "responseCode: " + response.getCode());
                Log.e(TAG, "Cookies after: " + cookieStore.getCookies().toString());
                List<Cookie> cookies = cookieStore.getCookies();
                String session_id = null;
                for (int n = 0; n < cookies.size(); n++) {
                    if (cookies.get(n).getName().equals("sessionid")) {
                        Log.d(TAG, "Cookie :" + cookies.get(n).getName() + "; value " + cookies.get(n).getValue());
                        session_id = cookies.get(n).getValue();
                    }
                }
                // If no session_id in response then kill login
                if (session_id == null) {
                    Log.e(TAG, "No session_id in response cookie");
                    m_settings.setSession(null);
                }
            } catch (ApiException e) {
                Crashlytics.log(e.toString());
                Crashlytics.setString("URL", url);
                if (m_parameters != null && !m_parameters.isEmpty()) {
                    Crashlytics.setString("params", new JSONObject(m_parameters).toString());
                }
                Crashlytics.logException(e);
            }
            response.close();
            return true;
        } catch (IOException e) {
            if (BuildConfig.DEBUG) {
                Log.w(TAG, "Network error", e);
            }
            Crashlytics.log(e.toString());
            Crashlytics.setString("URL", url);
            Crashlytics.logException(e);
            try {
                HttpEntity entity = response.getEntity();
                entity.getContent().close();
            } catch (Exception e1) {
            }
            request.abort();
            try {
                Thread.sleep(RETRY_INTERVAL);
            } catch (InterruptedException e1) {
            }
        }
    }
    return true;
}
Also used : HttpPost(org.apache.hc.client5.http.classic.methods.HttpPost) MultipartEntityBuilder(org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder) HttpEntity(org.apache.hc.core5.http.HttpEntity) ConnectivityManager(android.net.ConnectivityManager) MultipartEntityBuilder(org.apache.hc.client5.http.entity.mime.MultipartEntityBuilder) HttpGet(org.apache.hc.client5.http.classic.methods.HttpGet) ArrayList(java.util.ArrayList) URI(java.net.URI) GZIPInputStream(java.util.zip.GZIPInputStream) DefaultConnectionKeepAliveStrategy(org.apache.hc.client5.http.impl.DefaultConnectionKeepAliveStrategy) BasicNameValuePair(org.apache.hc.core5.http.message.BasicNameValuePair) CloseableHttpResponse(org.apache.hc.client5.http.impl.classic.CloseableHttpResponse) Cookie(org.apache.hc.client5.http.cookie.Cookie) BasicNameValuePair(org.apache.hc.core5.http.message.BasicNameValuePair) NameValuePair(org.apache.hc.core5.http.NameValuePair) HttpUriRequestBase(org.apache.hc.client5.http.classic.methods.HttpUriRequestBase) FileBody(org.apache.hc.client5.http.entity.mime.FileBody) NetworkInfo(android.net.NetworkInfo) UrlEncodedFormEntity(org.apache.hc.client5.http.entity.UrlEncodedFormEntity) IOException(java.io.IOException) IOException(java.io.IOException) ApiException(ee.ajapaik.android.exception.ApiException) JSONObject(org.json.JSONObject) StringBody(org.apache.hc.client5.http.entity.mime.StringBody) Map(java.util.Map) ApiException(ee.ajapaik.android.exception.ApiException)

Example 4 with FileBody

use of org.apache.hc.client5.http.entity.mime.FileBody in project selcukes-java by selcukes.

the class SlackUploader method uploadFile.

public void uploadFile(String filePath) {
    SlackFileUploader slackFileUploader = SlackFileUploader.builder().channel(ConfigFactory.getConfig().getNotifier().get("channel")).token(ConfigFactory.getConfig().getNotifier().get("api-token")).filePath(filePath).fileName("Sample").build();
    StringBuilder url = new StringBuilder();
    url.append(NotifierEnum.SLACK_API_URL.getValue()).append(slackFileUploader.getToken()).append("&channels=").append(slackFileUploader.getChannel()).append("&pretty=1");
    File fileToUpload = new File(slackFileUploader.getFilePath());
    FileBody fileBody = new FileBody(fileToUpload);
    IncomingWebHookRequest.forUrl(url.toString()).post(fileBody);
}
Also used : FileBody(org.apache.hc.client5.http.entity.mime.FileBody) File(java.io.File)

Example 5 with FileBody

use of org.apache.hc.client5.http.entity.mime.FileBody in project selcukes-java by selcukes.

the class WebClient method post.

public <T> Response post(T payload) {
    HttpEntity httpEntity = (payload instanceof FileBody) ? client.createMultipartEntity((FileBody) payload) : client.createStringEntity(payload);
    HttpPost post = client.createHttpPost(url, httpEntity);
    return new Response(client.createClient().execute(post));
}
Also used : HttpPost(org.apache.hc.client5.http.classic.methods.HttpPost) HttpEntity(org.apache.hc.core5.http.HttpEntity) FileBody(org.apache.hc.client5.http.entity.mime.FileBody)

Aggregations

FileBody (org.apache.hc.client5.http.entity.mime.FileBody)5 HttpPost (org.apache.hc.client5.http.classic.methods.HttpPost)4 HttpEntity (org.apache.hc.core5.http.HttpEntity)4 File (java.io.File)3 CloseableHttpResponse (org.apache.hc.client5.http.impl.classic.CloseableHttpResponse)3 IOException (java.io.IOException)2 StringBody (org.apache.hc.client5.http.entity.mime.StringBody)2 CloseableHttpClient (org.apache.hc.client5.http.impl.classic.CloseableHttpClient)2 ConnectivityManager (android.net.ConnectivityManager)1 NetworkInfo (android.net.NetworkInfo)1 ApiException (ee.ajapaik.android.exception.ApiException)1 FileNotFoundException (java.io.FileNotFoundException)1 URI (java.net.URI)1 Path (java.nio.file.Path)1 ArrayList (java.util.ArrayList)1 Map (java.util.Map)1 GZIPInputStream (java.util.zip.GZIPInputStream)1 UsernamePasswordCredentials (org.apache.hc.client5.http.auth.UsernamePasswordCredentials)1 HttpGet (org.apache.hc.client5.http.classic.methods.HttpGet)1 HttpUriRequestBase (org.apache.hc.client5.http.classic.methods.HttpUriRequestBase)1