import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.methods.PostMethod; import org.junit.Test; /** * @author ceshi * @Title: JunitTest * @ProjectName test * @Description: TODO * @date 2018/6/1416:39 */ public class JunitTest { @Test public void test(){ HttpClientPostMethod("http://localhost:8080/test/api","你好"); } public String HttpClientPostMethod(String url,String data){ //1.创建 HttpClient HttpClient httpClient = new HttpClient(); // 2.构造PostMethod的实例 PostMethod postMethod = new PostMethod(url); //3.请求参数 postMethod.addParameter("data", data); String responseMsg = ""; try { httpClient.executeMethod(postMethod); responseMsg = postMethod.getResponseBodyAsString().trim(); } catch (Exception e) { e.printStackTrace(); } finally { // 4.释放连接 postMethod.releaseConnection(); } return responseMsg; } }
maven pom需要添加
<dependency> <groupId>org.apache.httpcomponents</groupId> <artifactId>httpclient</artifactId> <version>4.5.3</version> </dependency> <dependency> <groupId>commons-httpclient</groupId> <artifactId>commons-httpclient</artifactId> <version>3.1</version> </dependency>