Java函数实现HTTP请求并获取响应的方法详解
HTTP请求是Web开发的基础之一,Java作为一种优秀的编程语言,在开发Web应用时,我们通常需要通过HTTP请求向其他系统获取数据或调用其他系统的API接口进行数据交互。本文将详细介绍Java如何实现HTTP请求并获取响应的方法。
1. Java中的HTTP请求方式
在Java中,我们可以通过URLConnection和HttpClient两种方式来实现HTTP请求,并获取响应结果。
1.1 URLConnection实现HTTP请求
URLConnection是JDK自带的一个类,它提供了一些方法来处理HTTP请求。通过使用URLConnection,我们可以创建一个连接对象,然后获取响应结果。具体步骤如下:
(1)通过URL类来创建一个URL对象
(2)通过URL对象的openConnection方法打开一个URLConnection对象
(3)设置请求方法,请求头等信息
(4)通过获取URLConnection对象的输入流读取响应结果
(5)使用完后,关闭连接
以获取百度热搜数据为例,代码如下:
public class UrlRequest {
public static void main(String[] args) {
try {
//创建URL对象
URL url = new URL("https://www.baidu.com/sugrec");
//打开URLConnection连接
URLConnection conn = url.openConnection();
//设置通用的请求属性
conn.setRequestProperty("Accept", "*/*");
conn.setRequestProperty("Connection", "keep-alive");
conn.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3");
//设置为POST请求
conn.setRequestMethod("POST");
//设置是否向httpUrlConnection输出,因为这个是post请求,参数要放在http正文内,所以要设为true
conn.setDoOutput(true);
//获取URLConnection对象对应的输出流
PrintWriter out = new PrintWriter(conn.getOutputStream());
//发送请求参数
out.print("prod=pc&from=pc_web&json=1&sid=1458_32848_33158_32893_31660_32721_22159_28004_33344_33337_33313_33344&hisdata=&source=&sugUUID=4d071ec2-706e-4509-8f58-8d27d42e9704&word=w");
//flush输出流的缓冲
out.flush();
//获取URLConnection对象对应的输入流
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//将输入流转换成字符串
String response = in.lines().collect(Collectors.joining());
System.out.println(response);
} catch (Exception e) {
System.out.println("发送POST请求出现异常!" + e);
e.printStackTrace();
}
}
}
1.2 HttpClient实现HTTP请求
HttpClient是Apache HttpComponents项目的子模块,它提供了一个完整的HTTP客户端,可以用来处理HTTP请求和响应。使用HttpClient的好处在于它提供了更加人性化和方便的API。具体步骤如下:
(1)创建CloseableHttpClient对象
(2)创建HttpGet或HttpPost方法
(3)设置请求头等信息
(4)使用execute方法执行请求,获取HttpResponse对象
(5)通过HttpResponse对象获取响应结果
(6)使用完后,关闭连接
以获取百度热搜数据为例,代码如下:
public class HttpClientRequest {
public static void main(String[] args) {
String url = "https://www.baidu.com/sugrec?prod=pc&from=pc_web&json=1&sid=1458_32848_33158_32893_31660_32721_22159_28004_33344_33337_33313_33344&hisdata=&source=&sugUUID=4d071ec2-706e-4509-8f58-8d27d42e9704&word=w";
//创建Http客户端
CloseableHttpClient httpClient = HttpClients.createDefault();
//创建HttpGet请求方法
HttpGet httpGet = new HttpGet(url);
try {
//执行HttpGet请求
CloseableHttpResponse response = httpClient.execute(httpGet);
//获取响应结果
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity);
System.out.println("响应内容为:" + result);
}
//关闭响应对象和Http客户端
EntityUtils.consume(entity);
response.close();
httpClient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. 请求参数的处理
HTTP请求中还需要向服务器传递请求参数,在Java中,可以通过参数拼接、JSON、表单等多种方式来实现,本文将介绍常见的三种处理方式。
2.1 参数拼接
在HTTP请求中,我们可以将参数拼接到URL地址的后面,例如:https://www.baidu.com/sugrec?prod=pc&from=pc_web&json=1&sid=1458_32848_33158_32893_31660_32721_22159_28004_33344_33337_33313_33344&hisdata=&source=&sugUUID=4d071ec2-706e-4509-8f58-8d27d42e9704&word=w。由于URL地址的长度有限制,所以拼接参数的方式适用于参数较少的情况。
2.2 JSON格式
在Java中,我们可以使用Jackson库将Java对象转换为JSON格式,然后将JSON作为参数传递给服务器。例如:
public class User {
private String name;
private int age;
//getter和setter方法
}
使用Jackson将User对象转换为JSON格式:
ObjectMapper mapper = new ObjectMapper();
User user = new User();
user.setName("张三");
user.setAge(20);
String json = mapper.writeValueAsString(user);
发送请求:
HttpPost httpPost = new HttpPost(url); StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON); httpPost.setEntity(entity);
2.3 表单格式
在Java中,我们也可以使用HttpClient提供的Form表单来传递参数。例如:
//创建HttpPost对象
HttpPost httpPost = new HttpPost(url);
//创建参数列表
ArrayList<NameValuePair> list = new ArrayList<NameValuePair>();
list.add(new BasicNameValuePair("param1", "value1"));
list.add(new BasicNameValuePair("param2", "value2"));
//将参数进行编码并放入HttpEntity中
HttpEntity entity = new UrlEncodedFormEntity(list, "UTF-8");
//设置请求头
httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
//设置请求实体
httpPost.setEntity(entity);
3. 响应结果的处理
在Java中,响应结果通常以字符串、字节数组、输入流等形式返回。我们可以通过读取响应结果获取所需要的信息。
3.1 字符串格式
如果响应结果是字符串格式,我们可以直接读取输入流并转换成字符串。例如:
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream())); String response = in.lines().collect(Collectors.joining());
或者:
HttpEntity entity = response.getEntity();
if (entity != null) {
String result = EntityUtils.toString(entity);
}
3.2 字节数组格式
如果响应结果是字节数组格式,我们可以先读取输入流到字节数组中,然后再根据需要转换为其他格式。例如:
InputStream inputStream = conn.getInputStream();
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
byte[] data = outStream.toByteArray();
3.3 输入流格式
如果响应结果是输入流格式,我们可以直接读取输入流并处理所需的信息。例如:
InputStream inputStream = response.getEntity().getContent();
4. 异常处理
在HTTP请求中,我们通常会遇到网络不稳定、请求超时等问题,为了保证程序的稳定性和健壮性,我们需要对异常进行处理。Java中,常见的异常有IOException
