cosmo

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理
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>

 

posted on 2018-06-14 17:34  【cosmo】  阅读(6668)  评论(0编辑  收藏  举报