HttpPost替换PostMethod
时间: 2023-12-04 12:45:33 浏览: 75
你可以使用 HttpClient 库来替换旧的 PostMethod 类。下面是一个示例代码,演示如何使用 HttpPost 来发送 POST 请求:
```java
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) throws IOException {
String url = "http://example.com/post";
// 创建 HttpClient 实例
HttpClient httpClient = HttpClientBuilder.create().build();
// 创建 HttpPost 请求
HttpPost httpPost = new HttpPost(url);
// 设置请求参数
List<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("param1", "value1"));
params.add(new BasicNameValuePair("param2", "value2"));
httpPost.setEntity(new UrlEncodedFormEntity(params));
// 发送请求并获取响应
HttpResponse response = httpClient.execute(httpPost);
// 获取响应内容
HttpEntity entity = response.getEntity();
String responseText = EntityUtils.toString(entity);
// 打印响应内容
System.out.println(responseText);
}
}
```
在上面的示例中,我们首先创建了一个 HttpClient 实例,然后创建了一个 HttpPost 请求,并设置了请求参数。最后,我们使用 HttpClient 发送了 POST 请求,并获取了响应。你可以根据自己的需求修改和扩展这个示例代码。
阅读全文