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


猜你喜欢
- 引言从前面我们可以大致了解了协程的玩法,如果一个协程中使用子协程,那么该协程会等待子协程执行结束后才真正退出,而达到这种效果的原因就是协程上
- List接口介绍—ArrayList有序、可重复线程不安全,因为没有synchronized修饰ArrayList源码结论ArrayList
- Flutter开发过程中,Drawer控件的使用频率也是比较高的,其实有过移动端开发经验的人来说,Flutter中的Drawer控件就相当于
- 零、关于HibernateHibernate是冬眠的意思,它是指动物的冬眠,但是本文讨论的Hibernate却与冬眠毫无关系,而是接下来要讨
- 一>实现功能在实验二中我们已经实现了在类微信界面添加recyclview并添加相应的imageview,本次实验就是在recyclvi
- 本文实例讲述了Android编程实现下载图片及在手机中展示的方法。分享给大家供大家参考,具体如下:在项目开发中从互联网上下载图片是经常用到的
- 尝试了各种防止中文乱码的方式,但是还是乱码;最后还是细节问题导致;解决方式:以及俩种方式是百度的,我的问题不是这俩块1.在requestMa
- 1.需要的Maven依赖// 支付宝<dependency> <groupId>com.alipay.
- 前言最近公司在重构广告系统,其中核心的打包功由广告系统调用,即对apk打包的调用和打包完成之后的回调,需要提供相应的接口给广告系统。因此,为
- 一、JDBC概述1、数据的持久化持久化(persistence):把数据保存到可掉电式存储设备中以供之后使用。大多数情况下,特别是企业级应用
- 一、WebSocket简介WebSocket协议通过在客户端和服务端之间提供全双工通信来进行Web和服务器的交互功能。在WebSocket应
- /**Bitmap放大的方法*/ private static Bitmap big(Bitmap bitmap) { Matrix mat
- 本文实例讲述了Android编程滑动效果之Gallery仿图像集浏览实现方法。分享给大家供大家参考,具体如下:Android系统自带一个Ga
- 场景点击拨打电话按钮,跳转到拨打电话页面点击发送短信按钮,跳转到发送短信页面注:实现将布局改为LinearLayout,并通过android
- C#之继承继承、封装和多态是面向对象编程的重要特性。其成员被继承的类叫基类也称父类,继承其成员的类叫派生类也称子类。派生类隐式获得基类的除构
- Android Rreact Native 常见错误总结 1.invariant violation:expecte
- 前文简单介绍了Android中SurfaceView的基本使用,本文就来介绍一下SurfaceView与多线程的混搭。SurfaceView
- 1,先取cantk-runtime-demos到本地:git clone https://github.com/drawapp8/cantk
- 在应用C#进行Winform窗体程序编写的时候,经常需要编写工具栏。下面小编给大家分享一下C#如何应用ToolSctrip控件编写工具栏。1
- 百度百科说法:Servlet(Server Applet)是Java Servlet的简称,称为小服务程序或服务连接器,用Java编写的服务