HttpClient一个开源的Java库用于发送HTTP请求和处理HTTP响应。它提供了一种简洁的方式来执行HTTP通信,并支持各种HTTP方法(如GET、POST、PUT、DELETE等),处理请求和响应的头部、实体和状态等。HttpClient可以用于构建Web应用程序、爬虫、客户端等,使得与HTTP相关的任务更加方便、灵活和高效。
HttpClient在springboot项目中只要的作用就是在方法内发送请求,此些请求一般为get和post类型的请求。
导入依赖
因为aliOss的依赖的底层依赖就是HttpClient所以我们可以直接使用Oss的依赖就可以。
<dependency><groupId>com.aliyun.oss</groupId><artifactId>aliyun-sdk-oss</artifactId><version>3.10.2</version></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.76</version></dependency>
创建HttpClient的工具类。
import com.alibaba.fastjson.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.fig.RequestConfig;
import org.apache.ity.UrlEncodedFormEntity;
import org.apache.hods.CloseableHttpResponse;
import org.apache.hods.HttpGet;
import org.apache.hods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.ity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.ssage.BasicNameValuePair;
import org.apache.http.util.EntityUtils;import java.io.IOException;
import java.URI;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;/*** Http工具类*/
public class HttpClientUtil {static final int TIMEOUT_MSEC = 5 * 1000;/*** 发送GET方式请求* @param url* @param paramMap* @return*/public static String doGet(String url,Map<String,String> paramMap){// 创建Httpclient对象CloseableHttpClient httpClient = ateDefault();String result = "";CloseableHttpResponse response = null;try{URIBuilder builder = new URIBuilder(url);if(paramMap != null){for (String key : paramMap.keySet()) {builder.addParameter((key));}}URI uri = builder.build();//创建GET请求HttpGet httpGet = new HttpGet(uri);//发送请求response = ute(httpGet);//判断响应状态StatusLine().getStatusCode() == 200){result = Entity(),"UTF-8");}}catch (Exception e){e.printStackTrace();}finally {try {response.close();httpClient.close();} catch (IOException e) {e.printStackTrace();}}return result;}/*** 发送POST方式请求* 参数携在路径中* @param url* @param paramMap* @return* @throws IOException*/public static String doPost(String url, Map<String, String> paramMap) throws IOException {// 创建Httpclient对象CloseableHttpClient httpClient = ateDefault();CloseableHttpResponse response = null;String resultString = "";try {// 创建Http Post请求HttpPost httpPost = new HttpPost(url);// 创建参数列表if (paramMap != null) {List<NameValuePair> paramList = new ArrayList();for (Map.Entry<String, String> param : Set()) {paramList.add(new Key(), Value()));}// 模拟表单UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);httpPost.setEntity(entity);}httpPost.setConfig(builderRequestConfig());// 执行http请求response = ute(httpPost);resultString = Entity(), "UTF-8");} catch (Exception e) {throw e;} finally {try {response.close();} catch (IOException e) {e.printStackTrace();}}return resultString;}/*** 发送POST方式请求* 且请求参数为Json类型。@RequsetParam* @param url* @param paramMap* @return* @throws IOException*/public static String doPost4Json(String url, Map<String, String> paramMap) throws IOException {// 创建Httpclient对象CloseableHttpClient httpClient = ateDefault();CloseableHttpResponse response = null;String resultString = "";try {// 创建Http Post请求HttpPost httpPost = new HttpPost(url);if (paramMap != null) {//构造json格式数据JSONObject jsonObject = new JSONObject();for (Map.Entry<String, String> param : Set()) {jsonObject.Key(),Value());}StringEntity entity = new String(),"utf-8");//设置请求编码entity.setContentEncoding("utf-8");//设置数据类型entity.setContentType("application/json");httpPost.setEntity(entity);}httpPost.setConfig(builderRequestConfig());// 执行http请求response = ute(httpPost);resultString = Entity(), "UTF-8");} catch (Exception e) {throw e;} finally {try {response.close();} catch (IOException e) {e.printStackTrace();}}return resultString;}private static RequestConfig builderRequestConfig() {return RequestConfig.custom().setConnectTimeout(TIMEOUT_MSEC).setConnectionRequestTimeout(TIMEOUT_MSEC).setSocketTimeout(TIMEOUT_MSEC).build();}}
在该工具类中,存在两个请求方式,Get,Post,在post中又存在两个方法,一个方法表示参数在路径中,还有个方法表示参数是一个参数体(Json类型)。
测试
当然我们也可以使用HttpClient原生来发送Get/post请求,工具类中本质的原理就是以下代码。
原生写法:
(localhost:8080/admin/employee/login 是一个编写好的用户登录接口)
@Testpublic void test3() throws Exception{//创建httpClientsCloseableHttpClient httpClient = ateDefault();//创建Post请求HttpPost httpPost = new HttpPost("localhost:8080/admin/employee/login");JSONObject jsonObject = new JSONObject();jsonObject.put("username", "admin");jsonObject.put("password", "123456");StringEntity stringEntity = new String());stringEntity.setContentType("application/json");stringEntity.setContentEncoding("utf-8");httpPost.setEntity(stringEntity);CloseableHttpResponse response = ute(httpPost);System.out.println("状态码为:" + StatusLine().getStatusCode());System.out.Entity().getContent());System.out.Entity()));httpClient.close();response.close();}
使用上述工具类的静态方法实现步骤为下:
@Testpublic void test4() throws Exception{HashMap<String, String> stringObjectHashMap = new HashMap<>();stringObjectHashMap.put("username", "admin");stringObjectHashMap.put("password", "123456");String s = HttpClientUtil.doPost4Json("localhost:8080/admin/employee/login", stringObjectHashMap);System.out.println(s);}
后续使用HttpClient是只需要引入HttpClientUtil即可,其代码是固定的,在springBoot项目的Controller方法中,在内部发送请求也就发送Get/Post情况最多,一般就是查询数据和提交数据。
本文发布于:2024-01-28 09:55:30,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/17064069356591.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |