使用HttpClient
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
public static String post(String url,String data) throws Exception {
String result = null;
try{
HttpClient httpClient = new HttpClient();
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
PostMethod postMethod = new PostMethod(url);
RequestEntity requestEntity = new StringRequestEntity(data,"application/json", "UTF-8");
postMethod.setRequestEntity(requestEntity);
postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
postMethod.addRequestHeader("Content-Type", "application/json");
httpClient.executeMethod(postMethod);
result = postMethod.getResponseBodyAsString();
postMethod.releaseConnection();
}catch (Exception e){
throw new Exception(e);
}
return result;
}
public static String get(String url) throws HttpException, Exception {
String result = null;
try {
HttpClient httpClient = new HttpClient();
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(15000);
GetMethod getMethod = new GetMethod(url);
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT, 60000);
getMethod.addRequestHeader("Content-Type", "application/json");
httpClient.executeMethod(getMethod);
result = getMethod.getResponseBodyAsString();
getMethod.releaseConnection();
}catch (Exception e){
throw new Exception(e);
}
return result;
}