POST请求用于向服务器发送数据; 例如,使用HTML表单的客户信息,文件上载等。
HttpClient API提供了一个名为HttpPost的类,它表示POST请求。
使用HttpClient库的HTTP POST请求。
第1步 - 创建HttpClient对象
HttpClients
类的createDefault()
方法返回类CloseableHttpClient
对象,该类是HttpClient
接口的基本实现。
使用此方法在HttpClient
对象上创建。
CloseableHttpClient httpClient = HttpClients.createDefault();
第2步 - 创建HttpPost对象HttpPost
类表示HTTP POST请求。它将发送所需数据并使用URI检索给定服务器的信息。
通过实例化HttpPost类并将表示URI的字符串值作为参数传递给其构造函数来创建此请求。
HttpGet httpGet = new HttpGet("http://www.kaops.com/");
第3步 - 执行获取请求CloseableHttpClient
对象的execute()
方法接受HttpUriRequest(接口)对象(即:HttpGet
,HttpPost
,HttpPut
,HttpHead
等)并返回响应对象。
HttpResponse httpResponse = httpclient.execute(httpget);
示例
以下是演示使用HttpClient库执行HTTP POST请求的示例。
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
public class HttpPostExample {
public static void main(String args[]) throws Exception{
//Creating a HttpClient object
CloseableHttpClient httpclient = HttpClients.createDefault();
//Creating a HttpGet object
HttpPost httppost = new HttpPost("http://www.kaops.com/");
//Printing the method used
System.out.println("Request Type: "+httppost.getMethod());
//Executing the Get request
HttpResponse httpresponse = httpclient.execute(httppost);
Scanner sc = new Scanner(httpresponse.getEntity().getContent());
//Printing the status line
System.out.println(httpresponse.getStatusLine());
while(sc.hasNext()){
System.out.println(sc.nextLine());
}
}
}
执行上面示例代码,得到以下结果 -
Request Type: POST
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>考评师 - 一个专注于面试题和知识测评的网站</title>
<meta name="baidu-site-verification" content="SMo5w14fvk" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="keywords" content="考试,面试,面试题,考试题">
<meta name="description" content="考评师网是一个专注于提供知识考评测试和面试题的网站。汇集了各个行业,各种技术,知识等面试题和知识测试。">
<link rel="stylesheet" href="/static/layui/css/layui.css">
<link rel="stylesheet" href="/static/css/global.css">
</head>
......