使用原始httpClient 实现 http post 请求
时间: 2023-11-23 22:08:09 浏览: 86
使用原始httpClient实现http post请求,可以按照以下步骤进行:
1. 创建一个HttpClient对象
```java
HttpClient client = new DefaultHttpClient();
```
2. 创建HttpPost请求对象,并设置请求的URL
```java
HttpPost post = new HttpPost("http://yoururl.com");
```
3. 创建请求参数,并设置到HttpPost对象中
```java
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", "value"));
post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
```
4. 执行HttpPost请求,并获取响应结果
```java
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
```
完整的代码示例:
```java
import java.util.ArrayList;
import java.util.List;
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.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class HttpPostExample {
public static void main(String[] args) {
try {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost("http://yoururl.com");
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", "value"));
post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse response = client.execute(post);
HttpEntity entity = response.getEntity();
String result = EntityUtils.toString(entity);
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
阅读全文