SpringBoot 接口开发教程(httpclient客户端)
更新时间:2022年03月09日 09:46:23 作者:纱布1213
这篇文章主要介绍了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; }
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
- SpringBoot实现对Http接口进行监控的代码
- springboot配置请求超时时间(Http会话和接口访问)
- springboot 实现Http接口加签、验签操作方法
- SpringBoot 项目使用hutool 工具进行 http 接口调用的处理方法
- Springboot单体架构http请求转换https请求来支持微信小程序调用接口
- SpringBoot使用RestTemplate实现HTTP请求详解
- springboot中RestTemplate配置HttpClient连接池详解
- 基于springboot的RestTemplate、okhttp和HttpClient对比分析
- SpringBoot如何使用Template请求http接口
相关文章
springboot集成nacos读取nacos配置数据的原理
这篇文章主要介绍了springboot集成nacos读取nacos配置数据的原理,文中有详细的代码流程,对大家学习springboot集成nacos有一定的帮助,需要的朋友可以参考下2023-05-05
最新评论