Java HttpClient PostMethod

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須要添加apache

<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>
相關文章
相關標籤/搜索