728x90
1.문제 코드
ObjectMapper objectMapper = new ObjectMapper();
String url = "http://주소.com";
// 2. set url of request
HttpPost post = new HttpPost(url);
// 3. set body
if(body != null){
StringEntity entity = new StringEntity(objectMapper.writeValueAsString(body));
post.setEntity(entity);
}
// set headers as json
Map<String, String> headers = new HashMap<>();
// set headers
headers.forEach((key, value)->{
log.info("header - {}:{}", key, value);
post.setHeader(key, value);
});
try (CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = httpClient.execute(post)) {
int status = response.getStatusLine().getStatusCode();
String text = new BufferedReader(
new InputStreamReader(response.getEntity().getContent(), StandardCharsets.UTF_8))
.lines()
.collect(Collectors.joining("\n"));
log.info("status:{}, entity:{}", status, text);
}
catch (UnsupportedOperationException | IOException e) {
log.error("error:", e);
throw e;
}
2. 코드 수정 & 추가
String entity encoding 수정
StringEntity entity = new StringEntity(objectMapper.writeValueAsString(body));
>
StringEntity entity = new StringEntity(objectMapper.writeValueAsString(body), "UTF-8");
header추가
Map<String, String> headers = new HashMap<>();
headers.put("Content-type", "application/json;charset=UTF-8");
headers.put("Accept", "application/json");
728x90
'개발 > java,spring,springboot' 카테고리의 다른 글
java exception 관리 - handling & safe (0) | 2021.08.18 |
---|---|
Apache http request 응용(+Springboot) (0) | 2021.04.22 |
spring boot Pbkf2PasswordEncoder 속도 빠르게 하기 (2) | 2021.04.09 |
spring boot query dsl (data source 여러개 설정) (1) | 2021.04.07 |
Spring boot jpa datasource 여러 개 설정(multiple datasource) (2) | 2021.04.07 |
댓글