概述调用HTTP的几种方式:
1. 使用FeignClient调用:Feign是一个声明式的Web Service客户端,它使得编写HTTP客户端变得更简单。通过FeignClient,你可以在代码中直接调用HTTP接口,而不需要手动编写HTTP请求和响应的处理逻辑。
2. 使用RestTemplate调用:RestTemplate是Spring框架提供的用于访问RESTful服务的工具类。它提供了多种HTTP请求方法(如GET、POST、PUT、DELETE等),并支持自定义HTTP消息转换器以处理HTTP请求和响应。
3. 使用AsyncHttpClient调用:AsyncHttpClient是一个异步的HTTP客户端库,它支持异步执行HTTP请求并返回异步结果。使用AsyncHttpClient可以有效地提高应用程序的性能和响应速度。
4. 使用HttpURLConnection调用:HttpURLConnection是Java内置的用于访问HTTP服务的API。它提供了HTTP请求和响应的基本功能,如设置请求头、发送GET/POST请求、获取响应状态码和响应体等。
5. 使用hutool调用:hutool是一个Java工具库,它提供了一些方便的工具类和方法,包括HTTP相关的功能。通过hutool,你可以轻松地发送HTTP请求并获取响应结果。
1.使用FeignClient调用
2.使用RestTemplate调用
3.使用AsyncHttpClient调用
4.使用HttpURLConnection调用
1.GET请求
2.POST请求
3.上传文件
4.Stream请求
5.使用hutool调用
1.案例FeignClient
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<!-- <version>4.0.1</version> -->
</dependency>
//启动类:@EnableFeignClients
@FeignClient(name = "masterdata",url = "${url}")
public interface ISysUserClient {
@GetMapping(value = "/masterdata/getSysUserById")
public Map getSysUserById(@RequestParam("userId") String userId);
}
2.RestTemplate
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
@Configuration
public class RestTemplateConfig {
@Bean
public RestTemplate restTemplate(ClientHttpRequestFactory factory){
return new RestTemplate(factory);
}
@Bean
public ClientHttpRequestFactory simpleClientHttpRequestFactory(){
SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
factory.setReadTimeout(1000);//单位为ms
factory.setConnectTimeout(1000);//单位为ms
return factory;
}
}
//测试
@RestController
public class Test {
@Resource
private RestTemplate restTemplate;
@GetMapping(value = "/save")
public void save(String userId) {
String url = "xxxxxx";
Map map = new HashMap<>();
map.put("name", "0000");
String results = restTemplate.postForObject(url, map, String.class);
}
}
3.AsyncHttpClient
4.Apache HttpClient
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
<version>4.5.13</version>
</dependency>
</dependencies>
public class GetClient {
/**
* GET---无参测试
*/
public void doGetTestOne(){
//获得http客户端
CloseableHttpClient client = HttpClientBuilder.create().build();
//创建get请求
HttpGet httpGet = new HttpGet("https://www.cuit.edu.cn/");
//响应模型
CloseableHttpResponse response = null;
try{
//有客户端指定get请求
response = client.execute(httpGet);
//从响应模型中获取响应体
HttpEntity responseEntity = response.getEntity();
System.out.println("响应状态为:"+response.getStatusLine());
if (responseEntity!=null){
System.out.println("响应内容长度为:"+responseEntity.getContentLength());
System.out.println("响应内容为:"+ EntityUtils.toString(responseEntity));
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try{
//释放资源
if(client!=null){
client.close();
}
if (response!=null){
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* GET--有参测试
*/
public void doGetTestWayOne(){
//获得http客户端
CloseableHttpClient client = HttpClientBuilder.create().build();
//参数
StringBuilder params = new StringBuilder();
try{
params.append("name=").append(URLEncoder.encode("&","utf-8")).append("&").append("age=24");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//创建Get请求
HttpGet httpGet = new HttpGet("https://www.cuit.edu.cn/?" + params);
//响应模型
CloseableHttpResponse response = null;
try{
//配置信息
RequestConfig config = RequestConfig.custom()
//设置连接超时时间
.setConnectTimeout(5000)
//设置请求超时时间
.setConnectionRequestTimeout(5000)
//socket读写超时时间
.setSocketTimeout(5000)
//设置是否允许重定向(默认为true)
.setRedirectsEnabled(true)
.build();
//将上面的配置信息配入Get请求中
httpGet.setConfig(config);
//由客户端执行Get请求
response = client.execute(httpGet);
//从响应模型中获取响应实体
HttpEntity responseEntity = response.getEntity();
System.out.println("响应状态为:"+response.getStatusLine());
if (responseEntity!=null){
System.out.println("响应内容长度为:"+responseEntity.getContentLength());
System.out.println("响应内容为:"+ EntityUtils.toString(responseEntity,"utf-8"));
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if(client!=null){
client.close();
}
if (response!=null){
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public void doGetTestWayTwo(){
CloseableHttpClient client = HttpClientBuilder.create().build();
URI uri = null;
try{
ArrayList<NameValuePair> params = new ArrayList<>();
params.add(new BasicNameValuePair("name","10"));
params.add(new BasicNameValuePair("age","18"));
//这里设置uri信息,并将参数集合放入uri;
//注: 这里也支持一个键值对一个键值对地往里面方setParameter(String key, String value)
uri = new URIBuilder().setScheme("http").setHost("www.cuit.edu.cn")
// .setPort(12345).setPath("/xw")
.setParameters(params).build();
System.out.println(uri);
} catch (URISyntaxException e) {
e.printStackTrace();
}
//创建httpGet请求
HttpGet httpGet = new HttpGet(uri);
//创建响应模型
CloseableHttpResponse response = null;
try{
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(5000)
.setConnectionRequestTimeout(5000)
.setSocketTimeout(5000)
.setRedirectsEnabled(true).build();
httpGet.setConfig(config);
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
System.out.println("响应状态码:"+response.getStatusLine());
System.out.println("响应内容长度:"+entity.getContentLength());
System.out.println("响应内容:"+EntityUtils.toString(entity,"utf-8"));
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//测试
public static void main(String[] args) {
//new GetClient().doGetTestOne();
//new GetClient().doGetTestWayOne();
new GetClient().doGetTestWayTwo();
}
}
public class PostClient {
/**
* POST 无参
*/
public void doPostTestOne(){
//获得http客户端
CloseableHttpClient client = HttpClientBuilder.create().build();
//创建Post请求
HttpPost httpPost = new HttpPost("https://www.cuit.edu.cn/index.htm");
//创建响应模型
CloseableHttpResponse response = null;
try{
response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
System.out.println("响应状态码:"+response.getStatusLine());
System.out.println("响应内容长度:"+entity.getContentLength());
System.out.println("响应内容:"+ EntityUtils.toString(entity,"utf-8"));
} catch (IOException e) {
e.printStackTrace();
}finally {
try{
if (client!=null){
client.close();
}
if (response!=null){
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* POST 有参
*/
public void doPostTestFour(){
//获的http客户端
CloseableHttpClient client = HttpClientBuilder.create().build();
//参数
StringBuilder params = new StringBuilder();
try{
//字符数据最好encoding; 这样一来, 某些特殊字符才嗯那个传过去(如:某人的名字就是"&",不encoding,传不过去)
params.append("phone=").append(URLEncoder.encode("admin","utf-8"));
params.append("&");
params.append("password=admin");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//创建post请求
HttpPost httpPost = new HttpPost("https://www.cuit.edu.cn/?" + params);
//设置ContentType(注:如果只是传入普通参数的话,ContentType不一定非要用application/json)
httpPost.setHeader("Content-Type","application/json;charset=utf-8");
//响应模型
CloseableHttpResponse response = null;
try{
response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
System.out.println("状态码:"+response.getStatusLine());
System.out.println("响应内容长度: "+entity.getContentLength());
System.out.println("响应内容: "+entity);
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* POST---有参测试(对象参数)
*/
public void doPostTestTwo(){
//获取Http客户端
CloseableHttpClient client = HttpClientBuilder.create().build();
//创建Post请求
HttpPost httpPost = new HttpPost("https://www.cuit.edu.cn/index.htm");
//User user = new User();
//user.setName("潘晓婷");
//user.setAge(18);
//user.setGender("女");
//user.setMotto("姿势要优雅~");
// 我这里利用阿里的fastjson,将Object转换为json字符串;
// (需要导入com.alibaba.fastjson.JSON包)
//String jsonString = JSON.toJSONString(user);
String jsonString = "";
StringEntity stringEntity = new StringEntity(jsonString, "utf-8");
httpPost.setEntity(stringEntity);
httpPost.setHeader("Content-Type", "application/json;charset=utf8");
CloseableHttpResponse response = null;
try{
response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
System.out.println("状态码:"+response.getStatusLine());
System.out.println("响应内容长度:"+entity.getContentLength());
System.out.println("响应内容:"+EntityUtils.toString(entity,"utf-8"));
} catch (IOException e) {
e.printStackTrace();
} finally {
try{
if (client!=null){
client.close();
}
if (response!=null){
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
//new PostClient().doPostTestOne();
//new PostClient().doPostTestFour();
new PostClient().doPostTestTwo();
}
}
public class FileClient {
/**
* 发送文件
注:如果想要灵活方便的传输文件的话,
* 除了引入org.apache.httpcomponents基本的httpclient依赖外
* 再额外引入org.apache.httpcomponents的httpmime依赖。
* 追注:即便不引入httpmime依赖,也是能传输文件的,不过功能不够强大。
*/
public void test4(){
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("https://www.cuit.edu.cn/file");
CloseableHttpResponse response = null;
try{
MultipartEntityBuilder multipartEntityBuilder = MultipartEntityBuilder.create();
//第一个文件
String fileKey = "files";
File file1 = new File("D:\\图片\\《Valorant》3440x1440带鱼屏游戏壁纸_彼岸图网.jpg");
/*
防止服务端收到的文件名乱码. 我们这里可以先将文件名URLEncode, 然后服务端拿到文件后URLDecode
文件名其实是放在请求头的Content-Disposition中 如其值form-data; name="files"; filename="头像.jpg"
*/
multipartEntityBuilder.addBinaryBody(fileKey,file1, ContentType.DEFAULT_BINARY, URLEncoder.encode(file1.getName(),"utf-8"));
//其他参数(注:自定义contentType,设置UTF-8是为了防止服务端拿到的参数出现乱码)
ContentType contentType = ContentType.create("text/plain", StandardCharsets.UTF_8);
multipartEntityBuilder.addTextBody("name","等沙利文",contentType);
multipartEntityBuilder.addTextBody("age","25",contentType);
HttpEntity httpEntity = multipartEntityBuilder.build();
httpPost.setEntity(httpEntity);
response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
if (entity!=null){
System.out.println("状态码:"+response.getStatusLine());
System.out.println("响应内容长度:"+entity.getContentLength());
System.out.println("响应内容:"+ EntityUtils.toString(entity,"utf-8"));
}
/*
File file1 = new File("D:\\图片\\XXX.jpg");
multipartEntityBuilder.addBinaryBody(fileKey,file1);
*/
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (client!=null){
client.close();
}
if (response!=null){
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new FileClient().test4();
}
}
public class StreamClient {
/**
* 发送流
*/
public void test5(){
CloseableHttpClient client = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("https://www.baidu.com/index.htm");
CloseableHttpResponse response = null;
try {
ByteArrayInputStream is = new ByteArrayInputStream("流~".getBytes(StandardCharsets.UTF_8));
InputStreamEntity ise = new InputStreamEntity(is);
httpPost.setEntity(ise);
response = client.execute(httpPost);
HttpEntity entity = response.getEntity();
System.out.println("响应状态码:"+response.getStatusLine());
if (entity!=null){
System.out.println("响应内容长度:"+entity.getContentLength());
System.out.println("响应内容:"+ EntityUtils.toString(entity,StandardCharsets.UTF_8));
}
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
if (client!=null){
client.close();
}
if (response!=null){
response.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
new StreamClient().test5();
}
}
5.hutool
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>4.5.1</version>
</dependency>
public static void main(String[] args){
// 1. 创建HttpRequest对象 - 指定好 url 地址
HttpRequest httpRequest = new HttpRequest("http://ip:port/test/");
// 2. 设置请求方式,默认是GET请求
httpRequest.setMethod(Method.GET);
// 3. 设置请求参数 可通过 form表单方法 设置
// form方法有很多重载方法,可以一个一个参数设置,也可以将参数封装进一个map集合然后一块儿传
Map<String, Object> paramsMap = new HashMap<>();
paramsMap.put("username","00");
httpRequest.form(paramsMap);
httpRequest.form("password", "123456");
httpRequest.form("username","ooo");
// 4. 设置请求头
// 请求头同样可以逐一设置,也可以封装到map中再统一设置
// 设置的请求头是否可以覆盖等信息具体请看源码关于重载方法的说明
httpRequest.header("x-c-authorization","yourToken");
// 5. 执行请求,得到http响应类
HttpResponse execute = httpRequest.execute();
// 6. 解析这个http响应类,可以获取到响应主体、cookie、是否请求成功等信息
boolean ok = execute.isOk(); // 是否请求成功 判断依据为:状态码范围在200~299内
System.out.println(ok);
List<HttpCookie> cookies = execute.getCookies();// 获取所有cookie
cookies.forEach(System.out::println); // 如果为空不会遍历的
String body = execute.body(); // 获取响应主体
System.out.println(body);
}