开发手册 欢迎您!
软件开发者资料库

Apache HttpClient - Http Post Request

Apache HttpClient Http Post Request - 从简单和简单的步骤学习Apache HttpClient,从基本到高级概念,包括概述,环境设置,Http Get请求,Http Post请求,响应处理程序,关闭连接,中止请求,拦截器,用户身份验证,使用代理,代理身份验证,基于表单的登录,Cookie管理,多线程,自定义SSL上下文,分段上传。

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.it1352.com/");

步骤3  - 执行获取请求

执行()方法CloseableHttpClient对象接受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.IT屋.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, Javai18n, GitLab, TestRail, VersionOne, DBUtils, Common CLI, Seaborn, Ansible,LOLCODE, Current Affairs 2018, Apache Commons Collections. . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . . . . . . . . . . .