Skip to content

Commit 80d1f8e

Browse files
committed
issue #424 byte[] getting converted to literal string of bits rather than a proper string
1 parent 070be51 commit 80d1f8e

File tree

2 files changed

+32
-4
lines changed

2 files changed

+32
-4
lines changed

unirest-bdd-tests/src/test/java/BehaviorTests/AsBytesTest.java

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -28,14 +28,18 @@
2828
import kong.unirest.Unirest;
2929
import org.junit.jupiter.api.Test;
3030

31+
import java.nio.charset.StandardCharsets;
32+
33+
import static org.junit.jupiter.api.Assertions.assertEquals;
34+
3135
class AsBytesTest extends BddTest {
3236
JacksonObjectMapper om = new JacksonObjectMapper();
3337

3438
@Test
3539
void getGetResultAsBytes() {
3640
byte[] content = Unirest.get(MockServer.GET)
37-
.asBytes()
38-
.getBody();
41+
.asBytes()
42+
.getBody();
3943

4044
RequestCapture cap = om.readValue(content, RequestCapture.class);
4145

@@ -57,15 +61,35 @@ void getGetResultAsBytesAsync() throws Exception {
5761
@Test
5862
void getGetResultAsBytesAsyncCallback() throws Exception {
5963
Unirest.get(MockServer.GET)
60-
.queryString("fruit","apple")
64+
.queryString("fruit", "apple")
6165
.asBytesAsync(r -> {
6266
RequestCapture cap = om.readValue(r.getBody(), RequestCapture.class);
63-
cap.assertParam("fruit","apple");
67+
cap.assertParam("fruit", "apple");
6468
asyncSuccess();
6569
})
6670
.get()
6771
.getBody();
6872

6973
assertAsync();
7074
}
75+
76+
@Test // https://github.com/Kong/unirest-java/issues/424
77+
void mappingErrorsFromAsBytes() {
78+
MockServer.setStringResponse("howdy");
79+
String r = Unirest.get(MockServer.ERROR_RESPONSE)
80+
.asBytes()
81+
.mapError(String.class);
82+
83+
assertEquals("howdy", r);
84+
}
85+
86+
@Test // https://github.com/Kong/unirest-java/issues/424
87+
void mappingErrorsFromAsBytesMapped() {
88+
MockServer.setJsonAsResponse(new Foo("howdy"));
89+
Foo r = Unirest.get(MockServer.ERROR_RESPONSE)
90+
.asBytes()
91+
.mapError(Foo.class);
92+
93+
assertEquals("howdy", r.bar);
94+
}
7195
}

unirest/src/main/java/kong/unirest/BaseResponse.java

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,7 @@
2525

2626
package kong.unirest;
2727

28+
import java.nio.charset.StandardCharsets;
2829
import java.util.Optional;
2930
import java.util.function.Consumer;
3031
import java.util.function.Function;
@@ -141,6 +142,9 @@ private String getErrorBody() {
141142
return null;
142143
}
143144
try {
145+
if(body instanceof byte[]){
146+
return new String((byte[])body, StandardCharsets.UTF_8);
147+
}
144148
return config.getObjectMapper().writeValue(body);
145149
} catch (Exception e) {
146150
return String.valueOf(body);

0 commit comments

Comments
 (0)