| 12345678910111213141516171819202122232425262728293031323334 |
- package Utils;
- import com.fasterxml.jackson.databind.ObjectMapper;
- import org.apache.http.HttpResponse;
- import org.apache.http.client.HttpClient;
- import org.apache.http.client.config.RequestConfig;
- import org.apache.http.client.methods.HttpPost;
- import org.apache.http.entity.StringEntity;
- import org.apache.http.impl.client.HttpClients;
- import org.apache.http.util.EntityUtils;
- import java.io.IOException;
- public class PostHelper {
- private static final HttpClient httpClient = HttpClients.createDefault();
- private static final int TIMEOUT = 30000;
- public static <T> String post(String url, T data) throws IOException {
- HttpPost httpPost = new HttpPost(url);
- RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(TIMEOUT).setConnectTimeout(TIMEOUT).build();
- httpPost.setConfig(requestConfig);
- httpPost.setHeader("Accept", "application/json");
- httpPost.setHeader("Content-Type", "application/json");
- ObjectMapper objectMapper = new ObjectMapper();
- httpPost.setEntity(new StringEntity(objectMapper.writeValueAsString(data), "UTF-8"));
- HttpResponse response = httpClient.execute(httpPost);
- String result = null;
- int statusCode = response.getStatusLine().getStatusCode();
- if (200 == statusCode) {
- result = EntityUtils.toString(response.getEntity());
- }
- httpPost.abort();
- return result;
- }
- }
|