用HttpClient实现RPC-get请求操作
package com.msb.httpclient;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Test;
import java.io.IOException;
import java.net.URISyntaxException;
/**
* @PackName com.msb.httpclient
* @Description: This program demonstrates 模拟浏览器发送 get 请求
* @Date 2022/6/10
* @Create by Uriel
* @Version 1.8
*/
public class HttpClientDemo {
@Test
public void testGetDemo() {
// 1. 创建一个http工具类,作用类似浏览器
CloseableHttpClient client = HttpClients.createDefault();
try {
// 2.获取 uri
URIBuilder uriBuilder = new URIBuilder("http://localhost:8080/demo");
uriBuilder.addParameter("param", "张三");
// 3. 发送 Get 请求
HttpGet httpGet = new HttpGet(uriBuilder.build());
// 4. 响应 Get 请求
CloseableHttpResponse response = client.execute(httpGet);
// 5. 将响应体HttpEntity转为字符串,并设置字符集编码
String res = EntityUtils.toString(response.getEntity(), "utf-8");
// 6. 打印响应结果
System.out.println(res);
// 7. 释放资源
response.close();
client.close();
} catch (URISyntaxException | IOException e) {
e.printStackTrace();
}
}
}
本文来自博客园,作者:wjxuriel,转载请注明原文链接:https://www.cnblogs.com/my-blog-site/p/16364015.html

浙公网安备 33010602011771号