I tried refactoring my code. After refactoring I am getting null response. Here is my older version of code:
import java.io.IOException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class GenericRestClientImpl implements GenericRestClient {
@Value("${auth.string}")
private String authString;
private static Logger logger = LogManager.getLogger(GenericRestClientImpl.class);
@Override
public String httpPostData(String jsonstr, String posturl) throws IOException {
String result = "";
HttpPost httpPost = new HttpPost(posturl);
httpPost.setEntity(new StringEntity(jsonstr, ContentType.APPLICATION_JSON));
httpPost.addHeader("Content-Type", "application/json");
httpPost.addHeader("Authorization", authString);
System.out.println("JSON to send: " + jsonstr);
logger.info("JSON to send: " + jsonstr);
try (CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
CloseableHttpResponse closeableHttpResponse = closeableHttpClient.execute(httpPost);) {
logger.info("response status code :" + closeableHttpResponse.getStatusLine().getStatusCode());
logger.info("response status line :" + closeableHttpResponse.getStatusLine());
result = EntityUtils.toString(closeableHttpResponse.getEntity());
logger.info("response data :" + result);
return result;
}
}
}
I want to refactor this to the Resttemplate. I have URL as String and JSON as String. How to refactor this? I tried several times but it didn't work. Is it not working because of variable type String?