httpclient 表单请求
时间: 2023-07-26 20:43:07 浏览: 95
好的,您可以使用 Apache HttpClient 来发送表单请求。以下是一个使用 HttpClient 发送 POST 请求并提交表单数据的示例代码:
```java
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class HttpClientFormPostExample {
public static void main(String[] args) throws IOException {
// 创建 HttpClient 实例
CloseableHttpClient httpClient = HttpClients.createDefault();
// 创建 HttpPost 请求,设置请求 URL
HttpPost httpPost = new HttpPost("http://example.com/form");
// 创建表单数据
List<NameValuePair> formParams = new ArrayList<>();
formParams.add(new BasicNameValuePair("username", "admin"));
formParams.add(new BasicNameValuePair("password", "123456"));
// 创建表单实体
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(formParams, StandardCharsets.UTF_8);
httpPost.setEntity(entity);
// 执行请求,获取响应
CloseableHttpResponse response = httpClient.execute(httpPost);
try {
// 处理响应
HttpEntity responseEntity = response.getEntity();
if (responseEntity != null) {
System.out.println(EntityUtils.toString(responseEntity));
}
} finally {
response.close();
}
}
}
```
在上面的代码中,我们首先创建了一个 HttpClient 实例,然后创建了一个 HttpPost 请求,并设置请求 URL。然后,我们创建了一个包含表单数据的 List 对象,并将其传递给一个 UrlEncodedFormEntity 对象,该对象将表单数据编码为 URL 编码格式的字符串。最后,我们将该实体设置为 HttpPost 请求的实体,并通过 HttpClient 执行该请求,最后处理响应。
阅读全文