Search in sources :

Example 51 with FileBody

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

the class RestClient method request.

private JSON request(HttpEntityEnclosingRequestBase req, File file) throws RestException, IOException {
    if (file != null) {
        File fileUpload = file;
        req.setHeader("X-Atlassian-Token", "nocheck");
        MultipartEntity ent = new MultipartEntity();
        ent.addPart("file", new FileBody(fileUpload));
        req.setEntity(ent);
    }
    return request(req);
}
Also used : FileBody(org.apache.http.entity.mime.content.FileBody) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) File(java.io.File)

Example 52 with FileBody

use of org.apache.http.entity.mime.content.FileBody in project fb-botmill by BotMill.

the class FbBotMillNetworkController method postFormDataMessage.

// TODO: used for attaching files but not working at the moment.
/**
 * POSTs a message as a JSON string to Facebook.
 *
 * @param recipient
 *            the recipient
 * @param type
 *            the type
 * @param file
 *            the file
 */
public static void postFormDataMessage(String recipient, AttachmentType type, File file) {
    String pageToken = FbBotMillContext.getInstance().getPageToken();
    // If the page token is invalid, returns.
    if (!validatePageToken(pageToken)) {
        return;
    }
    // TODO: add checks for valid attachmentTypes (FILE, AUDIO or VIDEO)
    HttpPost post = new HttpPost(FbBotMillNetworkConstants.FACEBOOK_BASE_URL + FbBotMillNetworkConstants.FACEBOOK_MESSAGES_URL + pageToken);
    FileBody filedata = new FileBody(file);
    StringBody recipientPart = new StringBody("{\"id\":\"" + recipient + "\"}", ContentType.MULTIPART_FORM_DATA);
    StringBody messagePart = new StringBody("{\"attachment\":{\"type\":\"" + type.name().toLowerCase() + "\", \"payload\":{}}}", ContentType.MULTIPART_FORM_DATA);
    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.STRICT);
    builder.addPart("recipient", recipientPart);
    builder.addPart("message", messagePart);
    // builder.addPart("filedata", filedata);
    builder.addBinaryBody("filedata", file);
    builder.setContentType(ContentType.MULTIPART_FORM_DATA);
    // builder.setBoundary("----WebKitFormBoundary7MA4YWxkTrZu0gW");
    HttpEntity entity = builder.build();
    post.setEntity(entity);
    // Logs the raw JSON for debug purposes.
    BufferedReader br;
    // post.addHeader("Content-Type", "multipart/form-data");
    try {
        // br = new BufferedReader(new InputStreamReader(
        // ())));
        Header[] allHeaders = post.getAllHeaders();
        for (Header h : allHeaders) {
            logger.debug("Header {} ->  {}", h.getName(), h.getValue());
        }
    // String output = br.readLine();
    } catch (Exception e) {
        e.printStackTrace();
    }
// postInternal(post);
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) FileBody(org.apache.http.entity.mime.content.FileBody) HttpEntity(org.apache.http.HttpEntity) Header(org.apache.http.Header) StringBody(org.apache.http.entity.mime.content.StringBody) BufferedReader(java.io.BufferedReader) IOException(java.io.IOException)

Example 53 with FileBody

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

the class HttpServerTest method testMultipartFormData.

@Test
public void testMultipartFormData() throws IOException {
    final int testPort = 4589;
    NanoHTTPD server = null;
    try {
        server = new NanoHTTPD(testPort) {

            final Map<String, String> files = new HashMap<String, String>();

            @Override
            public Response serve(IHTTPSession session) {
                StringBuilder responseMsg = new StringBuilder();
                try {
                    session.parseBody(this.files);
                    for (String key : files.keySet()) {
                        responseMsg.append(key);
                    }
                } catch (Exception e) {
                    responseMsg.append(e.getMessage());
                }
                return Response.newFixedLengthResponse(responseMsg.toString());
            }
        };
        server.start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://localhost:" + testPort);
        final String fileName = "file-upload-test.htm";
        FileBody bin = new FileBody(new File(getClass().getClassLoader().getResource(fileName).getFile()));
        StringBody comment = new StringBody("Filename: " + fileName);
        MultipartEntity reqEntity = new MultipartEntity();
        reqEntity.addPart("bin", bin);
        reqEntity.addPart("comment", comment);
        httppost.setEntity(reqEntity);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream instream = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(instream, "UTF-8"));
            String line = reader.readLine();
            assertNotNull(line, "Invalid server reponse");
            assertEquals("Server failed multi-part data parse" + line, "bincomment", line);
            reader.close();
            instream.close();
        }
    } finally {
        if (server != null) {
            server.stop();
        }
    }
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) FileBody(org.apache.http.entity.mime.content.FileBody) HttpEntity(org.apache.http.HttpEntity) InputStreamReader(java.io.InputStreamReader) HashMap(java.util.HashMap) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) NanoHTTPD(org.nanohttpd.protocols.http.NanoHTTPD) HttpResponse(org.apache.http.HttpResponse) IHTTPSession(org.nanohttpd.protocols.http.IHTTPSession) IOException(java.io.IOException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) Response(org.nanohttpd.protocols.http.response.Response) HttpResponse(org.apache.http.HttpResponse) StringBody(org.apache.http.entity.mime.content.StringBody) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) BufferedReader(java.io.BufferedReader) File(java.io.File) Test(org.junit.Test)

Example 54 with FileBody

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

the class HttpServerTest method testTempFileInterface.

@Test
public void testTempFileInterface() throws IOException {
    final int testPort = 4589;
    NanoHTTPD server = new NanoHTTPD(testPort) {

        final Map<String, String> files = new HashMap<String, String>();

        @Override
        public Response serve(IHTTPSession session) {
            String responseMsg = "pass";
            try {
                session.parseBody(this.files);
                for (String key : files.keySet()) {
                    if (!(new File(files.get(key))).exists()) {
                        responseMsg = "fail";
                    }
                }
            } catch (Exception e) {
                responseMsg = e.getMessage();
            }
            return Response.newFixedLengthResponse(responseMsg.toString());
        }
    };
    server.start(NanoHTTPD.SOCKET_READ_TIMEOUT, false);
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://localhost:" + testPort);
    final String fileName = "file-upload-test.htm";
    FileBody bin = new FileBody(new File(getClass().getClassLoader().getResource(fileName).getFile()));
    StringBody comment = new StringBody("Filename: " + fileName);
    MultipartEntity reqEntity = new MultipartEntity();
    reqEntity.addPart("bin", bin);
    reqEntity.addPart("comment", comment);
    httppost.setEntity(reqEntity);
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        InputStream instream = entity.getContent();
        BufferedReader reader = new BufferedReader(new InputStreamReader(instream, "UTF-8"));
        String line = reader.readLine();
        assertNotNull(line, "Invalid server reponse");
        assertEquals("Server file check failed: " + line, "pass", line);
        reader.close();
        instream.close();
    } else {
        fail("No server response");
    }
    server.stop();
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) FileBody(org.apache.http.entity.mime.content.FileBody) HttpEntity(org.apache.http.HttpEntity) InputStreamReader(java.io.InputStreamReader) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) NanoHTTPD(org.nanohttpd.protocols.http.NanoHTTPD) HttpResponse(org.apache.http.HttpResponse) IHTTPSession(org.nanohttpd.protocols.http.IHTTPSession) IOException(java.io.IOException) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) StringBody(org.apache.http.entity.mime.content.StringBody) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) DefaultHttpClient(org.apache.http.impl.client.DefaultHttpClient) HttpClient(org.apache.http.client.HttpClient) BufferedReader(java.io.BufferedReader) HashMap(java.util.HashMap) Map(java.util.Map) File(java.io.File) Test(org.junit.Test)

Example 55 with FileBody

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

the class AbstractStreamingAnalyticsService method postJob.

/**
 * Submit an application bundle to execute as a job.
 */
protected JsonObject postJob(CloseableHttpClient httpClient, JsonObject service, File bundle, JsonObject jobConfigOverlay) throws IOException {
    String url = getJobSubmitUrl(httpClient, bundle);
    HttpPost postJobWithConfig = new HttpPost(url);
    postJobWithConfig.addHeader(AUTH.WWW_AUTH_RESP, getAuthorization());
    FileBody bundleBody = new FileBody(bundle, ContentType.APPLICATION_OCTET_STREAM);
    StringBody configBody = new StringBody(jobConfigOverlay.toString(), ContentType.APPLICATION_JSON);
    HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("bundle_file", bundleBody).addPart("job_options", configBody).build();
    postJobWithConfig.setEntity(reqEntity);
    JsonObject jsonResponse = StreamsRestUtils.getGsonResponse(httpClient, postJobWithConfig);
    TRACE.info("Streaming Analytics service (" + getName() + "): submit job response:" + jsonResponse.toString());
    return jsonResponse;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) FileBody(org.apache.http.entity.mime.content.FileBody) HttpEntity(org.apache.http.HttpEntity) StringBody(org.apache.http.entity.mime.content.StringBody) JsonObject(com.google.gson.JsonObject)

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