Search in sources :

Example 16 with ForestMultipart

use of com.dtflys.forest.multipart.ForestMultipart in project forest by dromara.

the class TestUploadClient method testUploadPathMap.

/**
 * Test Path Collections *
 */
@Test
public void testUploadPathMap() throws InterruptedException, FileUploadException {
    server.enqueue(new MockResponse().setBody(EXPECTED));
    String path1 = this.getClass().getResource("/test-img.jpg").getPath();
    String path2 = this.getClass().getResource("/test-img2.jpg").getPath();
    Map<String, String> pathMap = new LinkedHashMap<>();
    pathMap.put("test-map-1.jpg", path1);
    pathMap.put("test-map-2.jpg", path2);
    for (String key : pathMap.keySet()) {
        String value = pathMap.get(key);
        if (isWindows() && value.startsWith("/")) {
            value = value.substring(1);
        }
        pathMap.put(key, value);
    }
    ForestRequest<Map> request = uploadClient.uploadPathMap(pathMap);
    assertNotNull(request);
    List<ForestMultipart> multipartList = request.getMultiparts();
    assertEquals(2, multipartList.size());
    // assertTrue(Map.class.isAssignableFrom(request.getLifeCycleHandler().getResultType()));
    int i = 1;
    for (ForestMultipart multipart : multipartList) {
        assertTrue(multipart instanceof FilePathMultipart);
        assertEquals("file", multipart.getName());
        File file = multipart.getFile();
        assertNotNull(file);
        assertEquals("test-map-" + i + ".jpg", multipart.getOriginalFileName());
        i++;
    }
    Map result = (Map) request.execute();
    assertNotNull(result);
    MockServerRequest.mockRequest(server).assertMultipart("file", fileItems -> {
        assertEquals(2, fileItems.size());
        FileItem fileItem1 = fileItems.get(0);
        assertEquals("test-map-1.jpg", fileItem1.getName());
        assertEquals("image/jpeg", fileItem1.getContentType());
        try {
            byte[] bytes = IOUtils.toByteArray(fileItem1.getInputStream());
            assertArrayEquals(IOUtils.toByteArray(new FileInputStream(path1)), bytes);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        FileItem fileItem2 = fileItems.get(1);
        assertEquals("test-map-2.jpg", fileItem2.getName());
        assertEquals("image/jpeg", fileItem2.getContentType());
        try {
            byte[] bytes = IOUtils.toByteArray(fileItem2.getInputStream());
            assertArrayEquals(IOUtils.toByteArray(new FileInputStream(path2)), bytes);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    });
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) ForestMultipart(com.dtflys.forest.multipart.ForestMultipart) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) LinkedHashMap(java.util.LinkedHashMap) FileItem(org.apache.commons.fileupload.FileItem) FilePathMultipart(com.dtflys.forest.multipart.FilePathMultipart) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) File(java.io.File) Test(org.junit.Test)

Example 17 with ForestMultipart

use of com.dtflys.forest.multipart.ForestMultipart in project forest by dromara.

the class HttpclientBodyBuilder method setFileBody.

@Override
protected void setFileBody(T httpReq, ForestRequest request, Charset charset, String contentType, LifeCycleHandler lifeCycleHandler) {
    String boundary = request.getBoundary();
    MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
    if (StringUtils.isNotEmpty(boundary)) {
        entityBuilder.setBoundary(boundary);
    }
    // 解决文件名乱码问题
    ForestJsonConverter jsonConverter = request.getConfiguration().getJsonConverter();
    Charset httpCharset = charset;
    Charset itemCharset = StandardCharsets.UTF_8;
    if (charset != null) {
        itemCharset = charset;
    }
    boolean needSetMode = false;
    for (ForestRequestBody item : request.body()) {
        if (item instanceof NameValueRequestBody) {
            needSetMode = true;
            NameValueRequestBody nameValueItem = (NameValueRequestBody) item;
            String name = nameValueItem.getName();
            Object value = nameValueItem.getValue();
            String partContentType = nameValueItem.getContentType();
            addMultipart(entityBuilder, name, value, partContentType, itemCharset, jsonConverter);
        } else if (item instanceof ObjectRequestBody) {
            Object obj = ((ObjectRequestBody) item).getObject();
            if (obj == null) {
                continue;
            }
            needSetMode = true;
            Map<String, Object> attrs = jsonConverter.convertObjectToMap(obj);
            for (Map.Entry<String, Object> entry : attrs.entrySet()) {
                String name = entry.getKey();
                Object value = entry.getValue();
                addMultipart(entityBuilder, name, value, null, itemCharset, jsonConverter);
            }
        }
    }
    if (needSetMode) {
        entityBuilder.setCharset(httpCharset);
        entityBuilder.setMode(HttpMultipartMode.RFC6532);
    }
    List<ForestMultipart> multiparts = request.getMultiparts();
    for (ForestMultipart multipart : multiparts) {
        String name = multipart.getName();
        String fileName = multipart.getOriginalFileName();
        String partContentType = multipart.getContentType();
        ContentType ctype = null;
        if (StringUtils.isNotEmpty(partContentType)) {
            ctype = ContentType.create(partContentType, httpCharset);
        }
        if (ctype == null) {
            String mimeType = URLConnection.guessContentTypeFromName(fileName);
            if (mimeType == null) {
                // guess this is a video uploading
                ctype = ContentType.create(com.dtflys.forest.backend.ContentType.MULTIPART_FORM_DATA, httpCharset);
            } else {
                ctype = ContentType.create(mimeType);
            }
        }
        AbstractContentBody contentBody = null;
        if (multipart.isFile()) {
            contentBody = new HttpclientMultipartFileBody(request, multipart.getFile(), ctype, fileName, lifeCycleHandler);
        } else {
            contentBody = new HttpclientMultipartCommonBody(request, multipart, ctype, fileName, lifeCycleHandler);
        }
        entityBuilder.addPart(name, contentBody);
    }
    HttpEntity entity = entityBuilder.build();
    httpReq.setEntity(entity);
}
Also used : AbstractContentBody(org.apache.http.entity.mime.content.AbstractContentBody) MultipartEntityBuilder(org.apache.http.entity.mime.MultipartEntityBuilder) ForestJsonConverter(com.dtflys.forest.converter.json.ForestJsonConverter) ContentType(org.apache.http.entity.ContentType) HttpEntity(org.apache.http.HttpEntity) ForestRequestBody(com.dtflys.forest.http.ForestRequestBody) ForestMultipart(com.dtflys.forest.multipart.ForestMultipart) ObjectRequestBody(com.dtflys.forest.http.body.ObjectRequestBody) Charset(java.nio.charset.Charset) NameValueRequestBody(com.dtflys.forest.http.body.NameValueRequestBody)

Example 18 with ForestMultipart

use of com.dtflys.forest.multipart.ForestMultipart in project forest by dromara.

the class TestUploadClient method testMixtureUploadImage.

@Test
public void testMixtureUploadImage() throws InterruptedException, FileUploadException {
    server.enqueue(new MockResponse().setBody(EXPECTED));
    String path = Objects.requireNonNull(this.getClass().getResource("/test-img.jpg")).getPath();
    if (path.startsWith("/") && isWindows()) {
        path = path.substring(1);
    }
    File file = new File(path);
    Map<String, Object> map = new HashMap<>();
    map.put("a", 1);
    map.put("b", 2);
    ForestRequest request = uploadClient.imageUploadWithMapParams("img1.jpg", file, map);
    assertNotNull(request);
    List<ForestMultipart> multipartList = request.getMultiparts();
    assertEquals(1, multipartList.size());
    ForestMultipart multipart = multipartList.get(0);
    // assertTrue(Map.class.isAssignableFrom(request.getMethod().getReturnClass()));
    assertTrue(multipart instanceof FileMultipart);
    assertEquals("file", multipart.getName());
    assertEquals("img1.jpg", multipart.getOriginalFileName());
    Map result = (Map) request.execute();
    assertNotNull(result);
    MockServerRequest.mockRequest(server).assertMultipart("file", multiparts -> {
        assertEquals(1, multiparts.size());
        FileItem fileItem = multiparts.get(0);
        assertEquals("img1.jpg", fileItem.getName());
        assertEquals("image/jpeg", fileItem.getContentType());
    }).assertMultipart("a", params -> {
        assertEquals(1, params.size());
        FileItem item = params.get(0);
        ContentType contentType = new ContentType(item.getContentType());
        assertEquals("text/plain", contentType.toStringWithoutParameters());
        try {
            assertEquals("1", IOUtils.toString(item.getInputStream()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }).assertMultipart("b", params -> {
        assertEquals(1, params.size());
        FileItem item = params.get(0);
        ContentType contentType = new ContentType(item.getContentType());
        assertEquals("text/plain", contentType.toStringWithoutParameters());
        try {
            assertEquals("2", IOUtils.toString(item.getInputStream()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    });
}
Also used : BeforeClass(org.junit.BeforeClass) URL(java.net.URL) ContentType(com.dtflys.forest.backend.ContentType) ForestRequest(com.dtflys.forest.http.ForestRequest) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Assert.assertThat(org.junit.Assert.assertThat) ForestConfiguration(com.dtflys.forest.config.ForestConfiguration) InputStreamMultipart(com.dtflys.forest.multipart.InputStreamMultipart) Map(java.util.Map) Assert.assertArrayEquals(org.junit.Assert.assertArrayEquals) MockWebServer(okhttp3.mockwebserver.MockWebServer) LinkedList(java.util.LinkedList) ForestMultipart(com.dtflys.forest.multipart.ForestMultipart) Assert.assertNotNull(org.junit.Assert.assertNotNull) FileItem(org.apache.commons.fileupload.FileItem) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) FileMultipart(com.dtflys.forest.multipart.FileMultipart) ByteArrayMultipart(com.dtflys.forest.multipart.ByteArrayMultipart) File(java.io.File) Objects(java.util.Objects) UploadClient(com.dtflys.test.http.client.UploadClient) IOUtils(org.apache.commons.io.IOUtils) List(java.util.List) JSON(com.alibaba.fastjson.JSON) Rule(org.junit.Rule) MockServerRequest(com.dtflys.forest.mock.MockServerRequest) StringUtils(com.dtflys.forest.utils.StringUtils) FilePathMultipart(com.dtflys.forest.multipart.FilePathMultipart) FileUploadException(org.apache.commons.fileupload.FileUploadException) MockResponse(okhttp3.mockwebserver.MockResponse) HttpBackend(com.dtflys.forest.backend.HttpBackend) Assert.assertEquals(org.junit.Assert.assertEquals) InputStream(java.io.InputStream) MockResponse(okhttp3.mockwebserver.MockResponse) FileMultipart(com.dtflys.forest.multipart.FileMultipart) ContentType(com.dtflys.forest.backend.ContentType) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ForestMultipart(com.dtflys.forest.multipart.ForestMultipart) ForestRequest(com.dtflys.forest.http.ForestRequest) IOException(java.io.IOException) FileItem(org.apache.commons.fileupload.FileItem) File(java.io.File) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) Test(org.junit.Test)

Example 19 with ForestMultipart

use of com.dtflys.forest.multipart.ForestMultipart in project forest by dromara.

the class TestUploadClient method testUploadInputStream.

@Test
public void testUploadInputStream() throws IOException, InterruptedException, FileUploadException {
    server.enqueue(new MockResponse().setBody(EXPECTED));
    String path = this.getClass().getResource("/test-img.jpg").getPath();
    if (path.startsWith("/") && isWindows()) {
        path = path.substring(1);
    }
    File file = new File(path);
    InputStream in = new FileInputStream(file);
    ForestRequest<Map> request = uploadClient.upload(in, "test-byte-array.jpg");
    assertNotNull(request);
    assertTrue(StringUtils.isNotEmpty(request.getBoundary()));
    List<ForestMultipart> multipartList = request.getMultiparts();
    assertEquals(1, multipartList.size());
    ForestMultipart multipart = multipartList.get(0);
    // assertTrue(Map.class.isAssignableFrom(request.getMethod().getReturnClass()));
    assertTrue(multipart instanceof InputStreamMultipart);
    assertEquals("file", multipart.getName());
    assertEquals("test-byte-array.jpg", multipart.getOriginalFileName());
    Map result = (Map) request.execute();
    assertNotNull(result);
    MockServerRequest.mockRequest(server).assertMultipart("file", fileItems -> {
        assertEquals(1, fileItems.size());
        FileItem fileItem = fileItems.get(0);
        assertEquals("test-byte-array.jpg", fileItem.getName());
        assertEquals("image/jpeg", fileItem.getContentType());
        try {
            byte[] bytes = IOUtils.toByteArray(fileItem.getInputStream());
            assertArrayEquals(IOUtils.toByteArray(new FileInputStream(file)), bytes);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    });
}
Also used : MockResponse(okhttp3.mockwebserver.MockResponse) ForestMultipart(com.dtflys.forest.multipart.ForestMultipart) FileInputStream(java.io.FileInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) FileItem(org.apache.commons.fileupload.FileItem) InputStreamMultipart(com.dtflys.forest.multipart.InputStreamMultipart) File(java.io.File) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) Test(org.junit.Test)

Example 20 with ForestMultipart

use of com.dtflys.forest.multipart.ForestMultipart in project forest by dromara.

the class TestUploadClient method testUploadPathList2.

@Test
public void testUploadPathList2() throws InterruptedException, FileUploadException {
    server.enqueue(new MockResponse().setBody(EXPECTED));
    URL[] urlArray = new URL[] { this.getClass().getResource("/test-img.jpg"), this.getClass().getResource("/test-img2.jpg") };
    List<String> pathList = new LinkedList<>();
    for (URL url : urlArray) {
        String path = getPathFromURL(url);
        pathList.add(path);
    }
    ForestRequest<Map> request = uploadClient.uploadPathList2(pathList);
    assertNotNull(request);
    List<ForestMultipart> multipartList = request.getMultiparts();
    assertEquals(2, multipartList.size());
    // assertTrue(Map.class.isAssignableFrom(request.getMethod().getReturnClass()));
    int i = 0;
    for (ForestMultipart multipart : multipartList) {
        assertTrue(multipart instanceof FilePathMultipart);
        assertEquals("file_" + i, multipart.getName());
        File file = multipart.getFile();
        assertNotNull(file);
        URL url = urlArray[i];
        assertEquals(getPathFromURL(url), file.getAbsolutePath().replaceAll("\\\\", "/"));
        assertEquals(getPathFromURL(url), ((FilePathMultipart) multipart).getFilePath());
        assertEquals("test-img-" + i + ".jpg", multipart.getOriginalFileName());
        i++;
    }
    Map result = (Map) request.execute();
    assertNotNull(result);
    MockServerRequest.mockRequest(server).assertMultipart("file_0", fileItems -> {
        assertEquals(1, fileItems.size());
        FileItem fileItem1 = fileItems.get(0);
        assertEquals("test-img-0.jpg", fileItem1.getName());
        assertEquals("image/jpeg", fileItem1.getContentType());
        try {
            byte[] bytes = IOUtils.toByteArray(fileItem1.getInputStream());
            URL url = urlArray[0];
            assertNotNull(url);
            assertArrayEquals(IOUtils.toByteArray(new FileInputStream(url.getFile())), bytes);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }).assertMultipart("file_1", fileItems -> {
        assertEquals(1, fileItems.size());
        FileItem fileItem1 = fileItems.get(0);
        assertEquals("test-img-1.jpg", fileItem1.getName());
        assertEquals("image/jpeg", fileItem1.getContentType());
        try {
            byte[] bytes = IOUtils.toByteArray(fileItem1.getInputStream());
            URL url = urlArray[1];
            assertNotNull(url);
            assertArrayEquals(IOUtils.toByteArray(new FileInputStream(url.getFile())), bytes);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    });
}
Also used : BeforeClass(org.junit.BeforeClass) URL(java.net.URL) ContentType(com.dtflys.forest.backend.ContentType) ForestRequest(com.dtflys.forest.http.ForestRequest) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Assert.assertThat(org.junit.Assert.assertThat) ForestConfiguration(com.dtflys.forest.config.ForestConfiguration) InputStreamMultipart(com.dtflys.forest.multipart.InputStreamMultipart) Map(java.util.Map) Assert.assertArrayEquals(org.junit.Assert.assertArrayEquals) MockWebServer(okhttp3.mockwebserver.MockWebServer) LinkedList(java.util.LinkedList) ForestMultipart(com.dtflys.forest.multipart.ForestMultipart) Assert.assertNotNull(org.junit.Assert.assertNotNull) FileItem(org.apache.commons.fileupload.FileItem) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) FileMultipart(com.dtflys.forest.multipart.FileMultipart) ByteArrayMultipart(com.dtflys.forest.multipart.ByteArrayMultipart) File(java.io.File) Objects(java.util.Objects) UploadClient(com.dtflys.test.http.client.UploadClient) IOUtils(org.apache.commons.io.IOUtils) List(java.util.List) JSON(com.alibaba.fastjson.JSON) Rule(org.junit.Rule) MockServerRequest(com.dtflys.forest.mock.MockServerRequest) StringUtils(com.dtflys.forest.utils.StringUtils) FilePathMultipart(com.dtflys.forest.multipart.FilePathMultipart) FileUploadException(org.apache.commons.fileupload.FileUploadException) MockResponse(okhttp3.mockwebserver.MockResponse) HttpBackend(com.dtflys.forest.backend.HttpBackend) Assert.assertEquals(org.junit.Assert.assertEquals) InputStream(java.io.InputStream) MockResponse(okhttp3.mockwebserver.MockResponse) ForestMultipart(com.dtflys.forest.multipart.ForestMultipart) IOException(java.io.IOException) URL(java.net.URL) LinkedList(java.util.LinkedList) FileInputStream(java.io.FileInputStream) FileItem(org.apache.commons.fileupload.FileItem) FilePathMultipart(com.dtflys.forest.multipart.FilePathMultipart) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) Map(java.util.Map) File(java.io.File) Test(org.junit.Test)

Aggregations

ForestMultipart (com.dtflys.forest.multipart.ForestMultipart)22 Map (java.util.Map)18 IOException (java.io.IOException)17 HashMap (java.util.HashMap)17 LinkedHashMap (java.util.LinkedHashMap)17 MockResponse (okhttp3.mockwebserver.MockResponse)17 FileItem (org.apache.commons.fileupload.FileItem)17 Test (org.junit.Test)17 FileInputStream (java.io.FileInputStream)16 URL (java.net.URL)14 File (java.io.File)13 ByteArrayMultipart (com.dtflys.forest.multipart.ByteArrayMultipart)11 FilePathMultipart (com.dtflys.forest.multipart.FilePathMultipart)11 LinkedList (java.util.LinkedList)10 ContentType (com.dtflys.forest.backend.ContentType)8 ForestRequest (com.dtflys.forest.http.ForestRequest)8 FileMultipart (com.dtflys.forest.multipart.FileMultipart)8 InputStreamMultipart (com.dtflys.forest.multipart.InputStreamMultipart)8 InputStream (java.io.InputStream)8 JSON (com.alibaba.fastjson.JSON)7