使用程式傳送http請求
阿新 • • 發佈:2018-12-06
需要jar包:
commons-httpclient.jar
commons-codec.jar
commons-logging.jar(或許不需要)
或依賴:
<!-- https://mvnrepository.com/artifact/commons-httpclient/commons-httpclient -->
<dependency>
<groupId>commons-httpclient</groupId>
<artifactId>commons-httpclient</artifactId>
<version>3.1</version>
</dependency>
程式碼:
//先建立一個連線物件
HttpClient client = new HttpClient();
//建立請求方法
HttpMethod postMethod = new PostMethod("http://127.0.0.1:8080/Test-WebApp/test");
//請求引數物件
NameValuePair[] params = new NameValuePair[]{new NameValuePair("aaa", "111")};
//把請求引數設定到請求方法裡
postMethod. setQueryString(params);
//執行請求
client.executeMethod(postMethod);
//獲取請求相應
String str = postMethod.getResponseBodyAsString();