HttpClient를 이용해서 API 통신을 하던 중 DELETE 메서드를 사용하게 되었다.
문서에 requestBody가 있는데 HttpDelete는 setEntity() 기능이 구현되지 않는다고..
사용하고 싶다면 HttpEntityEnclosingRequestBase를 상속받고 HttpPost를 따라서 새로운 클래스를 만들어 사용해야 한다.
package egovframework.gdms.common;
import java.net.URI;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.springframework.stereotype.Service;
@Service
public class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
public static final String METHOD_NAME = "DELETE";
@Override
public String getMethod(){
return METHOD_NAME;
}
public HttpDeleteWithBody(final String uri){
super();
setURI(URI.create(uri));
}
public HttpDeleteWithBody(final URI uri){
super();
setURI(uri);
}
public HttpDeleteWithBody(){
super();
}
}
@SuppressWarnings("deprecation")
public Object deleteApiJson(JSONObject jsonMain, String requestURL) throws Exception {
Object objData = null;
if(requestURL != null) {
HttpClient client = HttpClientBuilder.create().build();
HttpDeleteWithBody deleteRequest = new HttpDeleteWithBody (requestURL);
deleteRequest.setHeader("authToken", EgovProperties.getProperty("Newtrack.api.authKey"));
deleteRequest.setEntity(new StringEntity(jsonMain.toString(), StandardCharsets.UTF_8));
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
CloseableHttpResponse response = httpClient.execute(deleteRequest);
if(response.getStatusLine().getStatusCode() == 200) { //200일때가 성공
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(response.getEntity().getContent(), "UTF-8"));
String strBR = bufferedReader.readLine();
bufferedReader.close();
JSONParser jParser = new JSONParser(); //제이슨형식으로 파싱하기 위한 제이슨파서
objData = jParser.parse(strBR); //String body를 제이슨형식으로 파싱
}
}
return objData;
}
구웃~👍👍