前言
提示:这里可以添加本文要记录的大概内容:
例如:随着人工智能的不断发展,机器学习这门技术也越来越重要,很多人都开启了学习机器学习,本文就介绍了机器学习的基础内容。
提示:以下是本篇文章正文内容,下面案例可供参考
一、HttpClient
SpringCloud中服务和服务之间的调用全部是使用HttpClient,还有前面使用SolrJ中就封装了HttpClient,在调用SolrTemplate的saveBean方法时就调用HttpClient技术。
当前大部分项目暴漏出来的接口是Http请求,数据格式是JSON格式,但在一些老项目使用的仍然是webService。
HttpClient 提供的主要的功能
(1)实现了所有 HTTP 的方法(GET,POST,PUT,DELETE 等)
(2)支持自动转向
(3)支持 HTTPS 协议
(4)支持代理服务器等
二、使用方法
使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。
-
创建HttpClient对象。
-
创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。
-
如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HttpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。
-
调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。
-
调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。
-
释放连接。无论执行方法是否成功,都必须释放连接
三、使用步骤
导入依赖:
<dependencies>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.3</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.28</version>
</dependency>
</dependencies>
代码如下(示例):
package com.example.springbootsum.controller;
import com.alibaba.fastjson.JSONObject;
import com.example.springbootsum.utils.HttpUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import java.net.ConnectException;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Map;
/**
* @Author lx
* @Date 2022/1/5 9:45
* @description:
* @Version 0.1.0
*/
@RestController
@RequestMapping("/testHttp")
public class UserHttpController {
private static final String YQS_GOODS_DETAIL = "http://***/getDetails";
@RequestMapping("/showUsertestHttp")
@ResponseBody
public void aaa() throws ConnectException, UnknownHostException {
Map<String,Object> map = new HashMap<>();
map.put("aa",11);
String ss = "";
JSONObject jsonObject = HttpUtils.doPost(YQS_GOODS_DETAIL, map);
System.out.println(jsonObject);
}
}
代码如下(示例):
package com.example.springbootsum.utils;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.*;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
/**
* @Author lx
* @Date 2022/1/5 9:43
* @description:
* @Version 0.1.0
*/
public class HttpUtils {
private static final String AND_CODE = "&";
private static final String EQUAL_CODE = "=";
private static final String QUESTION_MARK = "?";
public static JSONObject doPost(String url, Map<String, Object> map) throws UnknownHostException, ConnectException {
JSONObject jsonObject = null;
//相当于建立一个http浏览器(http客户端)
HttpClient client = HttpClients.createDefault();
//将URL放入StringBuilder有助于字符串组合
StringBuilder stringBuffer = new StringBuilder(url);
StringBuffer sb = new StringBuffer();
stringBuffer.append(QUESTION_MARK);
if (null != map) {
Iterator iterator = map.entrySet().iterator();
while (iterator.hasNext()) {
Map.Entry<String, Object> next = (Map.Entry) iterator.next();
//组合url
sb.append(AND_CODE).append(next.getKey()).append(EQUAL_CODE).append(next.getValue() + "");
}
String param = sb.substring(1);
url = stringBuffer.append(param).toString();
}
//httpPost其实在服务端模拟浏览器向其它接口发送服务的
HttpPost post = new HttpPost(url); // 定义Post请求
// 构造最简单的字符串数据
StringEntity stringEntity = new StringEntity(url, "UTF-8");
// 设置内容格式
stringEntity.setContentType("application/json");
// 装入post中
post.setEntity(stringEntity);
post.setHeader("content-type", "application/json;charset=UTF-8");
HttpResponse execute = null;
try {
//执行
execute = client.execute(post);
if (execute.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
jsonObject = JSONObject.parseObject(EntityUtils.toString(execute.getEntity()));
}
} catch (IOException e) {
e.printStackTrace();
}
return jsonObject;
}
}