java httpclient发送post请求
时间: 2023-09-12 11:10:52 浏览: 166
java使用httpclient发送post请求示例
3星 · 编辑精心推荐
以下是Java HttpClient发送POST请求的示例代码:
```java
import java.io.BufferedReader;
import java.io.InputStreamReader;
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.entity.UrlEncodedFormEntity;
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 HttpClientPostExample {
public static void main(String[] args) {
CloseableHttpClient httpClient = HttpClients.createDefault();
try {
HttpPost httpPost = new HttpPost("http://example.com/api/post");
// 构造POST请求参数
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", "testuser"));
params.add(new BasicNameValuePair("password", "testpass"));
httpPost.setEntity(new UrlEncodedFormEntity(params));
// 发送POST请求
HttpResponse response = httpClient.execute(httpPost);
// 处理响应结果
System.out.println("Response Code : " + response.getStatusLine().getStatusCode());
HttpEntity entity = response.getEntity();
if (entity != null) {
BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent()));
String line = "";
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
EntityUtils.consume(entity);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
httpClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
```
该示例代码使用Apache HttpClient库发送POST请求,构造POST请求参数并设置到HttpEntity中,然后使用HttpClient.execute()方法发送请求并获取响应结果。最后使用EntityUtils.consume()方法释放资源。
阅读全文