随着spring boot越来越来流行,restful风格的接口也成为新的接口规范,spring MVC项目调用restful接口的工具类
import com.sun.xml.internal.fastinfoset.Encoder;
import org.apache.http.client.methods.*;
import org.apache.http.client.utils.URIBuilder;
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 java.io.IOException;
import java.net.URI;
public class HttpUtils {
public static String doGet(String url) {
CloseableHttpClient httpClient = HttpClients.createDefault();
String result = null;
CloseableHttpResponse response = null;
try {
URIBuilder builder = new URIBuilder(url);
URI uri = builder.build();
HttpGet httpGet = new HttpGet(uri);
response = httpClient.execute(httpGet);
result = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static String doPost(String url, String json) {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String result = null;
try {
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPost.setEntity(entity);
response = httpClient.execute(httpPost);
result = EntityUtils.toString(response.getEntity(), Encoder.UTF_8);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static String doPut(String url, String json) {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String result = null;
try {
HttpPut httpPut = new HttpPut(url);
StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
httpPut.setEntity(entity);
response = httpClient.execute(httpPut);
result = EntityUtils.toString(response.getEntity(), Encoder.UTF_8);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static String doDelete(String url) {
CloseableHttpClient httpClient = HttpClients.createDefault();
CloseableHttpResponse response = null;
String result = null;
try {
HttpDelete httpDelete = new HttpDelete(url);
response = httpClient.execute(httpDelete);
result = EntityUtils.toString(response.getEntity(), Encoder.UTF_8);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (response != null) {
response.close();
}
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
}