Search in sources :

Example 46 with MultipartEntity

use of org.apache.http.entity.mime.MultipartEntity in project product-iots by wso2.

the class HTTPInvoker method uploadFile.

public static HTTPResponse uploadFile(String url, String fileName, String fileContentType) {
    HttpPost post = null;
    HttpResponse response = null;
    HTTPResponse httpResponse = new HTTPResponse();
    CloseableHttpClient httpclient = null;
    try {
        httpclient = (CloseableHttpClient) createHttpClient();
        post = new HttpPost(url);
        File file = new File(fileName);
        MultipartEntity mpEntity = new MultipartEntity();
        ContentBody cbFile = new FileBody(file, fileContentType);
        mpEntity.addPart("file", cbFile);
        post.setEntity(mpEntity);
        post.setHeader(Constants.Header.AUTH, OAUTH_BEARER + oAuthToken);
        // post.setHeader(Constants.Header.CONTENT_TYPE, "multipart/form-data");
        post.setHeader("Accept", Constants.ContentType.APPLICATION_JSON);
        response = httpclient.execute(post);
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (KeyManagementException e) {
        e.printStackTrace();
    }
    BufferedReader rd = null;
    try {
        rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    } catch (IOException e) {
        e.printStackTrace();
    }
    StringBuffer result = new StringBuffer();
    String line = "";
    try {
        while ((line = rd.readLine()) != null) {
            result.append(line);
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    httpResponse.setResponseCode(response.getStatusLine().getStatusCode());
    httpResponse.setResponse(result.toString());
    try {
        httpclient.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return httpResponse;
}
Also used : HttpPost(org.apache.http.client.methods.HttpPost) CloseableHttpClient(org.apache.http.impl.client.CloseableHttpClient) FileBody(org.apache.http.entity.mime.content.FileBody) HTTPResponse(org.wso2.mdm.qsg.dto.HTTPResponse) HttpResponse(org.apache.http.HttpResponse) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) KeyStoreException(java.security.KeyStoreException) KeyManagementException(java.security.KeyManagementException) ClientProtocolException(org.apache.http.client.ClientProtocolException) ContentBody(org.apache.http.entity.mime.content.ContentBody) MultipartEntity(org.apache.http.entity.mime.MultipartEntity)

Example 47 with MultipartEntity

use of org.apache.http.entity.mime.MultipartEntity 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 48 with MultipartEntity

use of org.apache.http.entity.mime.MultipartEntity 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 49 with MultipartEntity

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

the class RestClient method request.

private JSON request(HttpEntityEnclosingRequestBase req, Issue.NewAttachment... attachments) throws RestException, IOException {
    if (attachments != null) {
        req.setHeader("X-Atlassian-Token", "nocheck");
        MultipartEntity ent = new MultipartEntity();
        for (Issue.NewAttachment attachment : attachments) {
            String filename = attachment.getFilename();
            Object content = attachment.getContent();
            if (content instanceof byte[]) {
                ent.addPart("file", new ByteArrayBody((byte[]) content, filename));
            } else if (content instanceof InputStream) {
                ent.addPart("file", new InputStreamBody((InputStream) content, filename));
            } else if (content instanceof File) {
                ent.addPart("file", new FileBody((File) content, filename));
            } else if (content == null) {
                throw new IllegalArgumentException("Missing content for the file " + filename);
            } else {
                throw new IllegalArgumentException("Expected file type byte[], java.io.InputStream or java.io.File but provided " + content.getClass().getName() + " for the file " + filename);
            }
        }
        req.setEntity(ent);
    }
    return request(req);
}
Also used : FileBody(org.apache.http.entity.mime.content.FileBody) MultipartEntity(org.apache.http.entity.mime.MultipartEntity) InputStream(java.io.InputStream) ByteArrayBody(org.apache.http.entity.mime.content.ByteArrayBody) InputStreamBody(org.apache.http.entity.mime.content.InputStreamBody) JSONObject(net.sf.json.JSONObject) File(java.io.File)

Example 50 with MultipartEntity

use of org.apache.http.entity.mime.MultipartEntity 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)

Aggregations

MultipartEntity (org.apache.http.entity.mime.MultipartEntity)62 HttpPost (org.apache.http.client.methods.HttpPost)41 StringBody (org.apache.http.entity.mime.content.StringBody)40 FileBody (org.apache.http.entity.mime.content.FileBody)37 File (java.io.File)31 HttpResponse (org.apache.http.HttpResponse)28 Test (org.junit.Test)24 TestHttpClient (io.undertow.testutils.TestHttpClient)13 IOException (java.io.IOException)13 InputStreamBody (org.apache.http.entity.mime.content.InputStreamBody)7 DefaultHttpClient (org.apache.http.impl.client.DefaultHttpClient)7 JSONObject (org.json.JSONObject)7 HashMap (java.util.HashMap)5 Map (java.util.Map)5 HttpEntity (org.apache.http.HttpEntity)5 ByteArrayBody (org.apache.http.entity.mime.content.ByteArrayBody)5 RequestBuilder (org.apache.sling.testing.tools.http.RequestBuilder)5 JSONException (org.json.JSONException)5 BlockingHandler (io.undertow.server.handlers.BlockingHandler)4 InputStream (java.io.InputStream)4