📅  最后修改于: 2020-11-18 08:26:43             🧑  作者: Mango
GET方法用于使用给定URI从给定服务器检索信息。使用GET的请求应仅检索数据,而对数据没有其他影响。
HttpClient API提供了一个名为HttpGet的类,该类表示get请求方法。
请按照下面给出的步骤使用HttpClient库发送获取请求
HttpClients类的createDefault()方法返回一个CloseableHttpClient对象,该对象是HttpClient接口的基本实现。
使用此方法,创建一个HttpClient对象,如下所示-
CloseableHttpClient httpclient = HttpClients.createDefault();
HttpGet类表示HTTPGET请求,该请求使用URI检索给定服务器的信息。
通过实例化此类创建一个HTTP GET请求。此类的构造函数接受表示URI的String值。
HttpGet httpget = new HttpGet("http://www.tutorialspoint.com/");
CloseableHttpClient类的execute()方法接受HttpUriRequest(接口)对象(即HttpGet,HttpPost,HttpPut,HttpHead等),并返回响应对象。
使用此方法执行请求,如下所示-
HttpResponse httpresponse = httpclient.execute(httpget);
下面的示例演示了使用HttpClient库执行HTTP GET请求的过程。
import java.util.Scanner;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
public class HttpGetExample {
public static void main(String args[]) throws Exception{
//Creating a HttpClient object
CloseableHttpClient httpclient = HttpClients.createDefault();
//Creating a HttpGet object
HttpGet httpget = new HttpGet("https://www.tutorialspoint.com/ ");
//Printing the method used
System.out.println("Request Type: "+httpget.getMethod());
//Executing the Get request
HttpResponse httpresponse = httpclient.execute(httpget);
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: GET
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
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . .