- 引入jar包
commonsHttpclient: 'commons-httpclient:commons-httpclient:3.1'
- 封装HttpRequestUtils
public class HttpRequestUtils {
private static final String CHARSET = "UTF-8";
private static final Logger log = LoggerFactory.getLogger(HttpRequestUtils.class);
/**
* 封装http的get请求工具
* @param url 请求地址拼接请求参数
* @return
*/
public static String doGet(String url){
HttpClient client = new HttpClient();
GetMethod get = new GetMethod(url);
get.setRequestHeader("Content-Type","application/json; charset=utf-8");
try {
log.info("开始执行API接口,url:{}",url);
int i = client.executeMethod(get);
if (i == 200){
byte[] responseBody = get.getResponseBody();
String response = new String(responseBody);
log.info("调用接口成功,response:{}",response);
return response;
}else {
log.error("调用API接口失败,url:{}",url);
return null;
}
} catch (IOException e) {
e.printStackTrace();
}finally {
// 关闭连接
get.releaseConnection();
}
return null;
}
/**
* 封装http的post清洁
* @param url 请求地址
* @param json 请求对象的json数据
* @return
*/
public static String doPost(String url, String json) {
HttpClient client = new HttpClient();
PostMethod post = new PostMethod(url);
post.setRequestHeader("Content-Type","application/json; charset=utf-8");
try{
RequestEntity requestEntity = new StringRequestEntity(json,"application/json",CHARSET);
log.info("开始执行API接口,url:{},RequestBody:{}",url,json);
post.setRequestEntity(requestEntity);
int i = client.executeMethod(post);
if (i == 200){
byte[] responseBody = post.getResponseBody();
String response = new String(responseBody);
log.info("调用API接口成功,response:{}",response);
return response;
}else {
log.error("调用API接口失败,url:{},RequestBody:{}",url,json);
return null;
}
}catch (IOException e) {
e.printStackTrace();
}finally {
// 关闭连接
post.releaseConnection();
}
return null;
}
}