PostHelper.java 1.4 KB

12345678910111213141516171819202122232425262728293031323334
  1. package Utils;
  2. import com.fasterxml.jackson.databind.ObjectMapper;
  3. import org.apache.http.HttpResponse;
  4. import org.apache.http.client.HttpClient;
  5. import org.apache.http.client.config.RequestConfig;
  6. import org.apache.http.client.methods.HttpPost;
  7. import org.apache.http.entity.StringEntity;
  8. import org.apache.http.impl.client.HttpClients;
  9. import org.apache.http.util.EntityUtils;
  10. import java.io.IOException;
  11. public class PostHelper {
  12. private static final HttpClient httpClient = HttpClients.createDefault();
  13. private static final int TIMEOUT = 30000;
  14. public static <T> String post(String url, T data) throws IOException {
  15. HttpPost httpPost = new HttpPost(url);
  16. RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(TIMEOUT).setConnectTimeout(TIMEOUT).build();
  17. httpPost.setConfig(requestConfig);
  18. httpPost.setHeader("Accept", "application/json");
  19. httpPost.setHeader("Content-Type", "application/json");
  20. ObjectMapper objectMapper = new ObjectMapper();
  21. httpPost.setEntity(new StringEntity(objectMapper.writeValueAsString(data), "UTF-8"));
  22. HttpResponse response = httpClient.execute(httpPost);
  23. String result = null;
  24. int statusCode = response.getStatusLine().getStatusCode();
  25. if (200 == statusCode) {
  26. result = EntityUtils.toString(response.getEntity());
  27. }
  28. httpPost.abort();
  29. return result;
  30. }
  31. }