- 引入pom文件
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
- 创建HttpClient对象实例化对象,分别对post和get请求进行处理
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.jetbrains.annotations.Contract;
import org.jetbrains.annotations.Nullable;
import java.io.IOException;
public class TestHttpClient {
public static void main(String[] args) throws IOException {
String urlParame="调用的url+参数";//正常的请求 例如https://***/index.php?m=jenkins&f=ajaxGetMainFuntion&type=function
System.out.println(sendPost(urlParame));
System.out.println(sendGet(urlParame));
}
//通过post请求
public static String sendPost(String urlParame) throws IOException {
//创建httpClient实例对象
HttpClient httpClient=new HttpClient();
//设置httpClient连接主机服务器超时时间: 以毫秒为单位 1000ms=1s,连接超时:为http连接主机服务器无法在规定时间内完成
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
//创建post请求方法实例对象
PostMethod postMethod=new PostMethod(urlParame);
//设置post请求超时时间,value单位为毫秒 请求超时:请求超时就是连接成功了,但你发出去的请求在指定时间内没有任何回应
postMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT,10000);
postMethod.addRequestHeader("Content-Type", "application/json");
//执行post
httpClient.executeMethod(postMethod);
//获得返回
String result=postMethod.getResponseBodyAsString();
//释放连接
postMethod.releaseConnection();
return result;
}
public static String sendGet(String urlParame) throws IOException {
//创建httpclient实例
HttpClient httpClient=new HttpClient();
//设置httpclient连接主机服务器超时时间: 以毫秒为单位 1000ms=1s
httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
//创建get请求方法实例对象
GetMethod getMethod=new GetMethod(urlParame);
//设置get请求超时时间,value以毫秒为单位
getMethod.getParams().setParameter(HttpMethodParams.SO_TIMEOUT,10000);
//设置请求头
getMethod.addRequestHeader("Content-Type", "application/json");
//执行get
httpClient.executeMethod(getMethod);
//获取返回数据
String result=getMethod.getResponseBodyAsString();
//释放http连接
getMethod.releaseConnection();
return result;
}
}
文章为转载,感谢原创,附上链接:https://blog.csdn.net/longshehe9319/article/details/80509829