Search in sources :

Example 6 with ContentType

use of com.dtflys.forest.backend.ContentType in project forest by dromara.

the class OkHttp3BodyBuilder method setFileBody.

@Override
protected void setFileBody(Request.Builder builder, ForestRequest request, Charset charset, String contentType, LifeCycleHandler lifeCycleHandler) {
    String boundary = request.getBoundary();
    MultipartBody.Builder bodyBuilder = null;
    if (StringUtils.isNotEmpty(boundary)) {
        bodyBuilder = new MultipartBody.Builder(boundary);
    } else {
        bodyBuilder = new MultipartBody.Builder();
    }
    ContentType objContentType = new ContentType(contentType);
    MediaType mediaType = MediaType.parse(objContentType.toStringWithoutParameters());
    if ("multipart".equals(mediaType.type())) {
        bodyBuilder.setType(mediaType);
    }
    ForestJsonConverter jsonConverter = request.getConfiguration().getJsonConverter();
    List<ForestMultipart> multiparts = request.getMultiparts();
    for (ForestRequestBody item : request.body()) {
        if (item instanceof NameValueRequestBody) {
            NameValueRequestBody nameValueItem = (NameValueRequestBody) item;
            String name = nameValueItem.getName();
            Object value = nameValueItem.getValue();
            String partContentType = nameValueItem.getContentType();
            addMultipart(bodyBuilder, name, value, partContentType, charset, jsonConverter);
        } else if (item instanceof ObjectRequestBody) {
            Object obj = ((ObjectRequestBody) item).getObject();
            if (obj == null) {
                continue;
            }
            Map<String, Object> attrs = jsonConverter.convertObjectToMap(obj);
            for (Map.Entry<String, Object> entry : attrs.entrySet()) {
                String name = entry.getKey();
                Object value = entry.getValue();
                addMultipart(bodyBuilder, name, value, null, charset, jsonConverter);
            }
        }
    }
    for (ForestMultipart multipart : multiparts) {
        RequestBody fileBody = createFileBody(request, multipart, charset, lifeCycleHandler);
        bodyBuilder.addFormDataPart(multipart.getName(), multipart.getOriginalFileName(), fileBody);
    }
    MultipartBody body = bodyBuilder.build();
    builder.method(request.getType().getName(), body);
}
Also used : ForestJsonConverter(com.dtflys.forest.converter.json.ForestJsonConverter) ContentType(com.dtflys.forest.backend.ContentType) ForestMultipart(com.dtflys.forest.multipart.ForestMultipart) ForestRequestBody(com.dtflys.forest.http.ForestRequestBody) ObjectRequestBody(com.dtflys.forest.http.body.ObjectRequestBody) NameValueRequestBody(com.dtflys.forest.http.body.NameValueRequestBody) Map(java.util.Map) ForestRequestBody(com.dtflys.forest.http.ForestRequestBody) ObjectRequestBody(com.dtflys.forest.http.body.ObjectRequestBody) NameValueRequestBody(com.dtflys.forest.http.body.NameValueRequestBody)

Example 7 with ContentType

use of com.dtflys.forest.backend.ContentType in project forest by dromara.

the class OkHttp3ForestResponse method setupContentTypeAndCharset.

/**
 * @author designer[19901753334@163.com]
 * @date 2021/12/8 23:51
 */
private void setupContentTypeAndCharset() {
    MediaType mediaType = body.contentType();
    if (mediaType != null) {
        String type = mediaType.type();
        String subType = mediaType.subtype();
        this.contentType = new ContentType(type, subType);
        Charset charset = mediaType.charset();
        if (charset != null) {
            this.charset = charset.name();
            return;
        }
    }
    setupResponseCharset();
}
Also used : ContentType(com.dtflys.forest.backend.ContentType) MediaType(okhttp3.MediaType) Charset(java.nio.charset.Charset)

Example 8 with ContentType

use of com.dtflys.forest.backend.ContentType in project forest by dromara.

the class TestUploadClient method testMixtureUploadImageWithJSONBodyParams.

@Test
public void testMixtureUploadImageWithJSONBodyParams() 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.imageUploadWithJSONBodyParams("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("params", params -> {
        assertEquals(1, params.size());
        FileItem item = params.get(0);
        ContentType contentType = new ContentType(item.getContentType());
        assertEquals("application/json", contentType.toStringWithoutParameters());
        try {
            assertEquals(JSON.toJSONString(map), 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 9 with ContentType

use of com.dtflys.forest.backend.ContentType in project forest by dromara.

the class AbstractBodyBuilder method buildBody.

/**
 * 构建请求体
 * @param httpRequest 后端http请求对象
 * @param request Forest请求对象
 * @param lifeCycleHandler 生命周期处理器
 */
@Override
public void buildBody(T httpRequest, ForestRequest request, LifeCycleHandler lifeCycleHandler) {
    String contentType = request.getContentType();
    if (StringUtils.isEmpty(contentType)) {
        contentType = ContentType.APPLICATION_X_WWW_FORM_URLENCODED;
    }
    String[] typeGroup = contentType.split(";[ ]*charset=");
    String mineType = typeGroup[0];
    String strCharset = request.getCharset();
    Charset charset = null;
    boolean mergeCharset = typeGroup.length > 1;
    if (StringUtils.isEmpty(strCharset)) {
        if (typeGroup.length > 1) {
            strCharset = typeGroup[1];
            charset = Charset.forName(strCharset);
        } else {
            charset = StandardCharsets.UTF_8;
        }
    } else {
        charset = Charset.forName(strCharset);
    }
    if (StringUtils.isEmpty(mineType)) {
        mineType = ContentType.APPLICATION_X_WWW_FORM_URLENCODED;
    }
    ContentType mineContentType = new ContentType(mineType);
    String ctypeWithoutParams = mineContentType.toStringWithoutParameters();
    ForestEncoder encoder = request.getEncoder();
    if (encoder != null) {
        byte[] bodyBytes = encoder.encodeRequestBody(request, charset);
        setBinaryBody(httpRequest, request, charset, ctypeWithoutParams, bodyBytes, mergeCharset);
        return;
    }
    ForestBody reqBody = request.getBody();
    boolean needRequestBody = request.getType().isNeedBody() || !reqBody.isEmpty() || !request.getMultiparts().isEmpty();
    if (needRequestBody) {
        ForestDataType bodyType = request.bodyType();
        if (bodyType == null || bodyType == ForestDataType.AUTO) {
            bodyType = mineContentType.bodyType();
        }
        if (bodyType == ForestDataType.MULTIPART) {
            setFileBody(httpRequest, request, charset, ctypeWithoutParams, lifeCycleHandler);
            return;
        }
        ForestEncoder bodyEncoder = (ForestEncoder) request.getConfiguration().getConverterMap().get(bodyType);
        if (bodyEncoder == null) {
            bodyEncoder = (ForestEncoder) request.getConfiguration().getConverterMap().get(ForestDataType.TEXT);
        }
        byte[] bodyBytes = bodyEncoder.encodeRequestBody(request, charset);
        setBinaryBody(httpRequest, request, charset, ctypeWithoutParams, bodyBytes, mergeCharset);
    }
}
Also used : ForestEncoder(com.dtflys.forest.converter.ForestEncoder) ForestBody(com.dtflys.forest.http.ForestBody) ContentType(com.dtflys.forest.backend.ContentType) Charset(java.nio.charset.Charset) ForestDataType(com.dtflys.forest.utils.ForestDataType)

Example 10 with ContentType

use of com.dtflys.forest.backend.ContentType 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)

Aggregations

ContentType (com.dtflys.forest.backend.ContentType)11 IOException (java.io.IOException)6 ForestRequest (com.dtflys.forest.http.ForestRequest)5 ForestMultipart (com.dtflys.forest.multipart.ForestMultipart)5 File (java.io.File)5 Map (java.util.Map)5 JSON (com.alibaba.fastjson.JSON)4 HttpBackend (com.dtflys.forest.backend.HttpBackend)4 ForestConfiguration (com.dtflys.forest.config.ForestConfiguration)4 MockServerRequest (com.dtflys.forest.mock.MockServerRequest)4 ByteArrayMultipart (com.dtflys.forest.multipart.ByteArrayMultipart)4 FileMultipart (com.dtflys.forest.multipart.FileMultipart)4 FilePathMultipart (com.dtflys.forest.multipart.FilePathMultipart)4 InputStreamMultipart (com.dtflys.forest.multipart.InputStreamMultipart)4 StringUtils (com.dtflys.forest.utils.StringUtils)4 UploadClient (com.dtflys.test.http.client.UploadClient)4 FileInputStream (java.io.FileInputStream)4 InputStream (java.io.InputStream)4 URL (java.net.URL)4 HashMap (java.util.HashMap)4