SpringBoot 接口开发教程(httpclient客户端)
作者:纱布1213 发布时间:2023-05-08 17:31:34
标签:SpringBoot,接口,httpclient,客户端
SpringBoot接口开发
服务端
@RestController
@RequestMapping("/landary")
public class landaryController {
@RequestMapping("adduser")
public JSONObject addUser(@RequestBody JSONObject userEntity)
{
System.out.println(JSONObject.toJSONString(userEntity));
JSONObject json=new JSONObject();
json.fluentPut("code","500").fluentPut("result",userEntity);
return json;
}
@RequestMapping("showuser")
public Object showUser()
{
return JSON.toJSONString("hhh");
}
}
客户端post请求
public static String sendSms(String uid,String title,String content){
HttpClient httpclient = new DefaultHttpClient();
String smsUrl="http://127.0.0.1:8088/landary/adduser";
HttpPost httppost = new HttpPost(smsUrl);
String strResult = "";
try {
JSONObject jobj = new JSONObject();
jobj.put("uid", uid);
jobj.put("title", title);
jobj.put("content",content);
System.out.println(jobj.toString());
// nameValuePairs.add(new BasicNameValuePair("msg", (jobj.toString())));
/* httppost.addHeader("Content-type", "application/json; charset=utf-8");
httppost.setHeader("Accept", "application/json");
httppost.setEntity(new StringEntity(jobj.toString(), Charset.forName("UTF-8")));*/
StringEntity s = new StringEntity(jobj.toString());
s.setContentEncoding("UTF-8");
s.setContentType("application/json");//发送json数据需要设置contentType
httppost.setEntity(s);
HttpResponse response = httpclient.execute(httppost);
if (response.getStatusLine().getStatusCode() == 200) {
/*读返回数据*/
String conResult = EntityUtils.toString(response
.getEntity());
System.out.println(conResult);
JSONObject sobj = new JSONObject();
sobj = JSONObject.parseObject(conResult);
String result = sobj.getString("result");
String code = sobj.getString("code");
if(code.equals("500")){
System.out.println(result);
strResult += "发送成功";
}else{
strResult += "发送失败,"+code;
}
} else {
String err = response.getStatusLine().getStatusCode()+"";
strResult += "发送失败:"+err;
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return strResult;
}
get请求
/**
* 发送 get请求
*/
public void get() {
CloseableHttpClient httpclient = HttpClients.createDefault();
try {
// 创建httpget.
HttpGet httpget = new HttpGet("http://127.0.0.1:8088/landary/showuser");
System.out.println("executing request " + httpget.getURI());
// 执行get请求.
CloseableHttpResponse response = httpclient.execute(httpget);
try {
// 获取响应实体
HttpEntity entity = response.getEntity();
System.out.println("--------------------------------------");
// 打印响应状态
System.out.println(response.getStatusLine());
if (entity != null) {
// 打印响应内容长度
System.out.println("Response content length: " + entity.getContentLength());
// 打印响应内容
System.out.println("Response content: " + EntityUtils.toString(entity));
}
System.out.println("------------------------------------");
} finally {
response.close();
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (ParseException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关闭连接,释放资源
try {
httpclient.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
SpringBoot之httpclient使用
超文本传输协议(HTTP,HyperText Transfer Protocol)是互联网上应用最为广泛的一种网络协议。所有的WWW文件都必须遵守这个标准。而HttpClient是可以支持http相关协议的工具包
它有如下功能:
1.实现了所有的http方法(GET,POST,PUT,HEAD 等)
2.支持自动转向
3.支持 HTTPS 协议
4.支持代理服务器等
既然HttpClient使用这么广泛,则本文讲解下Spring Boot 中怎么使用HttpClient.如下:
引入相关依赖
<!-- http所需包 -->
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpmime</artifactId>
</dependency>
<!-- /http所需包 -->
<!-- 数据解析所需包 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.6</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.4</version>
</dependency>
<!-- /数据解析所需包 -->
编写相关工具类
写个http的工具类,以便业务代码直接调用,如下:
/**
* Http工具类
*/
public class HttpUtils {
/**
* 发送POST请求
* @param url 请求url
* @param data 请求数据
* @return 结果
*/
@SuppressWarnings("deprecation")
public static String doPost(String url, String data) {
CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom()
.setSocketTimeout(10000).setConnectTimeout(20000)
.setConnectionRequestTimeout(10000).build();
httpPost.setConfig(requestConfig);
String context = StringUtils.EMPTY;
if (!StringUtils.isEmpty(data)) {
StringEntity body = new StringEntity(data, "utf-8");
httpPost.setEntity(body);
}
// 设置回调接口接收的消息头
httpPost.addHeader("Content-Type", "application/json");
CloseableHttpResponse response = null;
try {
response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
context = EntityUtils.toString(entity, HTTP.UTF_8);
} catch (Exception e) {
e.getStackTrace();
} finally {
try {
response.close();
httpPost.abort();
httpClient.close();
} catch (Exception e) {
e.getStackTrace();
}
}
return context;
}
/**
* 解析出url参数中的键值对
* @param url url参数
* @return 键值对
*/
public static Map<String, String> getRequestParam(String url) {
Map<String, String> map = new HashMap<String, String>();
String[] arrSplit = null;
// 每个键值为一组
arrSplit = url.split("[&]");
for (String strSplit : arrSplit) {
String[] arrSplitEqual = null;
arrSplitEqual = strSplit.split("[=]");
// 解析出键值
if (arrSplitEqual.length > 1) {
// 正确解析
map.put(arrSplitEqual[0], arrSplitEqual[1]);
} else {
if (arrSplitEqual[0] != "") {
map.put(arrSplitEqual[0], "");
}
}
}
return map;
}
}
业务代码中使用
业务中代码使用,拼装请求Url和请求数据,就可以调用工具类里的doPost()方法开始直接使用咯。如下:
private String getFileStorePath(String courtId, String seesionId){
String fileStorePath = StringUtils.EMPTY;
//请求参数
String data = "{\"courtId\":\"" + courtId + "\",\"sessionId\":\"" + seesionId + "\"}";
String fileServiceUrl="http://111.11.11.11:8086";
//发送请求,获取结果
String result = HttpUtils.doPost(fileServiceUrl + "/ms-service/voice/search", data);
if(StringUtils.isNotBlank(result)){
com.alibaba.fastjson.JSONObject jsonobject = JSON.parseObject(result);
fileStorePath = jsonobject.getString("path");
logger.info("fileStorePath = " + fileStorePath);
}
return fileStorePath;
}
来源:https://blog.csdn.net/u011992073/article/details/76827200
0
投稿
猜你喜欢
- 1. 基本用法<dependency> <groupId>org.redisson</groupI
- 上一次接触到编码的知识,还是上大学的时候,那时候学的是通信工程专业,有关编码的内容,不记得是在通信原理还是信息论与编码里面学到的了。却依然记
- 前言在分布式场景下为了保证数据最终一致性。在单进程的系统中,存在多个线程可以同时改变某个变量(可变共享变量)时,就需要对变量或代码块做同步(
- 这篇文章主要介绍了SpringBoot FreeWorker模板技术解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考
- 过滤器实现过滤器需要实现 javax.servlet.Filter 接口。重写三个方法。其中 init() 方法在服务启动时执行,destr
- 本文实例讲述了DevExpress设置饼状图的Lable位置的方法。分享给大家供大家参考。具体实现方法如下:关键代码如下:/// <s
- Shiro是什么Shiro是一个Java平台的开源权限框架,用于认证和访问授权。具体来说,满足对如下元素的支持:用户,角色,权限(仅仅是操作
- 一,引入dll1.ServiceStack.Common.dll2.ServiceStack.Interfaces.dll3.Service
- 本文主要为大家整理Java常见的面试题,供大家参考,具体内容如下1. Java中sleep和wait的区别① 这两个方法来自不同
- 测试spring cloud 使用consul注册服务的时候,出现critical,如下:怎么解决这个问题,现在只能看到health che
- 前言在Java System#exit 无法退出程序的问题一文末尾提到优雅停机的一种实现方案,要借助Shutdown Hook进行实现,本文
- 最近在学习springmvc,今天把springmvc 参数绑定给整理一下,也算个学习笔记吧!@RequestParam 绑定单个请求Req
- 本文分享了如何对Dubbo服务进行优雅的参数校验,以实现服务端统一的数据返回格式,同时也在一定程度提升开发效率,避免重复简单的参数校验逻辑.
- 前言回调的核心就是回调方将本身即this传递给调用方,这样调用方就可以在调用完毕之后告诉回调方它想要知道的信息。1、什么是回调软件模块之间总
- 一、在pom.xml中配置jetty插件: <build> <plugins> <p
- 生成1. 生成error 文件的路径:你可以通过参数设置-XX:ErrorFile=/path/hs_error%p.log, 默认是在Ja
- 本文实例讲述了c#图像截取的实现方法。分享给大家供大家参考。具体如下:图像截取的相关代码如下: public Form1()&nb
- IDEA设置Tab选项卡本人喜欢把tab选项卡全部放出来(tab选项卡默认是10个,超过后会把最先打开的挤出去,像队列一样先进先出),比如这
- 简介我们在开发web应用的时候,有时候为了适应浏览器大小的调整,需要动态对页面的组件进行位置的调整。这时候就会用到flow layout,也
- 一般入参我们都会转为vo对象。那么直接在对象的属性上注解即可。 其实spring用的是hibernate的validator.步骤1.配置s