public class HttpUtils {
/**
* post 请求<br>
*
* @param url
* @param jsonObject
* @return
*/
public static String requestPost(String url, String parameters) {
String body = null;
if (StringUtilsExtends.isNotBlank(url)) {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost method = new HttpPost(url);
if (method != null && StringUtilsExtends.isNotBlank(parameters)) {
try {
method.addHeader("Content-type",
"application/json; charset=utf-8");
method.setHeader("Accept", "application/json");
method.setEntity(new StringEntity(parameters, Charset
.forName("UTF-8")));
CloseableHttpResponse response = httpClient.execute(method);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
body = EntityUtils.toString(response.getEntity(),
"utf-8");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
method.releaseConnection();
}
}
}
return body;
}
/**
* put 请求<br>
*
* @param url
* @param jsonObject
* @return
*/
public static String requestPut(String url, String parameters, String token) {
String body = null;
if (StringUtilsExtends.isNotBlank(url)) {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPut method = new HttpPut(url);
if (method != null && StringUtilsExtends.isNotBlank(parameters)) {
try {
method.addHeader("Content-type",
"application/json; charset=utf-8");
method.setHeader("Accept", "application/json");
method.setHeader("X-Auth-Token", token);
method.setEntity(new StringEntity(parameters, Charset
.forName("UTF-8")));
CloseableHttpResponse response = httpClient.execute(method);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_CREATED) {
body = EntityUtils.toString(response.getEntity(),
"utf-8");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
method.releaseConnection();
}
}
}
return body;
}
/**
* get 请求<br>
*
* @param url
* @param jsonObject
* @return
*/
public static String requestGet(String url, String token) {
String body = null;
if (StringUtilsExtends.isNotBlank(url)
&& StringUtilsExtends.isNotBlank(token)) {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpGet method = new HttpGet(url);
try {
if (method != null) {
method.addHeader("Content-type",
"application/json; charset=utf-8");
method.setHeader("Accept", "application/json");
method.setHeader("X-Auth-Token", token);
// 配置请求的超时设置
// RequestConfig requestConfig = RequestConfig.custom()
// .setConnectionRequestTimeout(1000)
// .setConnectTimeout(1000).setSocketTimeout(1000).build();
// method.setConfig(requestConfig);
CloseableHttpResponse response = httpClient.execute(method);
int statusCode = response.getStatusLine().getStatusCode();
if (statusCode == HttpStatus.SC_OK) {
body = EntityUtils.toString(response.getEntity());
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
method.releaseConnection();
}
}
return body;
}
}
HTTP POST GET PUT请求处理
最新推荐文章于 2024-08-05 23:16:41 发布