📅  最后修改于: 2020-11-18 08:27:04             🧑  作者: Mango
POST请求用于将数据发送到服务器;例如使用HTML表单的客户信息,文件上传等。
HttpClient API提供了一个名为HttpPost的类,该类表示POST请求。
请按照下面给出的步骤使用HttpClient库发送HTTP POST请求。
HttpClients类的createDefault()方法返回CloseableHttpClient类的对象,该对象是HttpClient接口的基本实现。
使用此方法,创建一个HttpClient对象。
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost类表示HTTP POST请求。这将发送所需的数据,并使用URI检索给定服务器的信息。
通过实例化HttpPost类并创建一个表示URI的字符串值作为其构造函数的参数来创建此请求。
HttpGet httpGet = new HttpGet("http://www.tutorialspoint.com/");
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("https://www.tutorialspoint.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
Parallax Scrolling, Java Cryptography, YAML, Python Data Science, Java
i18n, GitLab, TestRail, VersionOne, DBUtils, Common CLI, Seaborn, Ansible,
LOLCODE, Current Affairs 2018, Apache Commons Collections
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .