在一些业务中我们可要调其他的接口(第三方的接口) 这样就用到我接下来用到的工具类。
用这个类需要引一下jar包的坐标

       <dependency><groupId>org.jsoup</groupId><artifactId>jsoup</artifactId><version>1.11.3</version></dependency>

引好坐标后就可以使用这个工具类了;

Connection.Response post = HttpUtils.post("http://localhost:10090/Controller/httpToJson",str);
String body = post.body();
System.out.println("响应报文:"+body);

str代表你需要传的参数 一般是json类型的数据

访问成功后一般会返回你一个json的数据,但是这个数据有一些问题,它会进行转译。我把这个字符串进行了一些处理。

{"result":"{\"FoodID\":\"A66J54DW9IKJ75U3\",\"FoodName\":\"桃子\",\"FoodBrand\":\"龙冠\",\"FoodPlace\":\"吉林\",\"FoodText\":\"四打击我家的娃哦哦囧\",\"FoodImg\":\"sdasdasdasd\",\"FoodProInfo\":[{\"ProjectName\":\"浇水\",\"UserName\":\"周锐\",\"OperationDescribe\":\"给桃子树浇水茁壮成长\",\"ImgUrl\":\"asdlpalplpd23\",\"OperationTm\":\"20200616103856\"}],\"FoodPackInfo\":null,\"FoodDetectionInfo\":null,\"FoodLogInfo\":null}","code":0,"message":"查询智能合约成功"}

对这个串进行替换等一些操作,然后把它转成json对象。通过json工具类把它自动封装到实体类型中,
(在进行封装实体的时候一定要注意,json串的属性和实体的属性要完全相同)否则会报错的(避免入坑)

 Connection.Response post = HttpUtils.post("http://localhost:10090/fabricController/queryChaincode",str);String body = post.body();String replace = body.replace("\\\"", "\"");String replace1 = replace.replace(":\"{", ":{");String replace2 = replace1.replace("}\",", "},");String replace3 = replace2.replace("{\"result\":", "");String replace4 = replace3.replace(",\"code\":0,\"message\":\"查询智能合约成功\"}", "");            com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(replace4);FoodAllInfo foodAllInfo = JSON.parseObject(replace4, FoodAllInfo.class);
package com.gblfy.order.utils;import org.jsoup.Connection;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;import javax.net.ssl.*;
import java.io.*;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;public class HttpUtils {/*** 请求超时时间*/private static final int TIME_OUT = 120000;/*** Https请求*/private static final String HTTPS = "https";/*** 发送Get请求** @param url 请求URL* @return 服务器响应对象* @throws IOException*/public static Response get(String url) throws IOException {return get(url, null);}/*** 发送Get请求** @param url     请求URL* @param headers 请求头参数* @return 服务器响应对象* @throws IOException*/public static Response get(String url, Map<String, String> headers) throws IOException {if (null == url || url.isEmpty()) {throw new RuntimeException("The request URL is blank.");}// 如果是Https请求if (url.startsWith(HTTPS)) {getTrust();}Connection connection = Jsoup.connect(url);connection.method(Connection.Method.GET);connection.timeout(TIME_OUT);connection.ignoreHttpErrors(true);connection.ignoreContentType(true);if (null != headers) {connection.headers(headers);}Response response = connection.execute();return response;}/*** 发送JSON格式参数POST请求** @param url    请求路径* @param params JSON格式请求参数* @return 服务器响应对象* @throws IOException*/public static Response post(String url, String params) throws IOException {return doPostRequest(url, null, null, null, params);}/*** 发送JSON格式参数POST请求** @param url     请求路径* @param headers 请求头中设置的参数* @param params  JSON格式请求参数* @return 服务器响应对象* @throws IOException*/public static Response post(String url, Map<String, String> headers, Map<String, String> params,String flag) throws IOException {return doPostRequest(url,headers,params,null,null);}/*** 字符串参数post请求** @param url      请求URL地址* @param paramMap 请求字符串参数集合* @return 服务器响应对象* @throws IOException*/public static Response post(String url, Map<String, String> headers) throws IOException {return doPostRequest(url, headers, null, null, null);}/*** 带上传文件的post请求** @param url      请求URL地址* @param paramMap 请求字符串参数集合* @param fileMap  请求文件参数集合* @return 服务器响应对象* @throws IOException*/public static Response post(String url, Map<String, String> paramMap, Map<String, File> fileMap)throws IOException {return doPostRequest(url, null, paramMap, fileMap, null);}/*** 执行post请求** @param url      请求URL地址* @param paramMap 请求字符串参数集合* @param fileMap  请求文件参数集合* @return 服务器响应对象* @throws IOException*/private static Response doPostRequest(String url, Map<String, String> headers, Map<String, String> paramMap,Map<String, File> fileMap, String jsonParams) throws IOException {if (null == url || url.isEmpty()) {throw new RuntimeException("The request URL is blank.");}// 如果是Https请求if (url.startsWith(HTTPS)) {getTrust();}Connection connection = Jsoup.connect(url);connection.method(Connection.Method.POST);connection.timeout(TIME_OUT);connection.ignoreHttpErrors(true);connection.ignoreContentType(true);if (null != headers) {connection.headers(headers);}// 收集上传文件输入流,最终全部关闭List<InputStream> inputStreamList = null;try {// 添加文件参数if (null != fileMap && !fileMap.isEmpty()) {inputStreamList = new ArrayList<InputStream>();InputStream in = null;File file = null;Set<Entry<String, File>> set = fileMap.entrySet();for (Entry<String, File> e : set) {file = e.getValue();in = new FileInputStream(file);inputStreamList.add(in);connection.data(e.getKey(), file.getName(), in);}}// 设置请求体为JSON格式内容else if (null != jsonParams && !jsonParams.isEmpty()) {connection.header("Content-Type", "application/json;charset=UTF-8");connection.requestBody(jsonParams);}// 普通表单提交方式else {connection.header("Content-Type", "application/x-www-form-urlencoded");}// 添加字符串类参数if (null != paramMap && !paramMap.isEmpty()) {connection.data(paramMap);}Response response = connection.execute();return response;} catch (FileNotFoundException e) {throw e;} catch (IOException e) {throw e;}// 关闭上传文件的输入流finally {if (null != inputStreamList) {for (InputStream in : inputStreamList) {try {in.close();} catch (IOException e) {e.printStackTrace();}}}}}/*** 获取服务器信任*/private static void getTrust() {try {HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {@Overridepublic boolean verify(String hostname, SSLSession session) {return true;}});SSLContext context = SSLContext.getInstance("TLS");context.init(null, new X509TrustManager[] { new X509TrustManager() {@Overridepublic void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {}@Overridepublic void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {}@Overridepublic X509Certificate[] getAcceptedIssuers() {return new X509Certificate[0];}} }, new SecureRandom());HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());} catch (Exception e) {e.printStackTrace();}}
}

发送http和https请求工具类 Json封装数据相关推荐

  1. .NET WebApi调用微信接口Https请求工具类

    .NET WebApi调用微信接口Https请求工具类 using System; using System.Collections.Generic; using System.IO; using S ...

  2. http和https请求工具类

    https请求 @Slf4j public class HttpPostUtils {public static int RESPONSE_STATUS_OK = 0;public static JS ...

  3. Java Https请求工具类

    个人技术网站 欢迎关注 由于微信API接口建议使用Https请求方式 而且过不久就废弃http请求方式了 所以提供以下Https工具类 public class SSLClient extends D ...

  4. HttpClient发起Http/Https请求工具类

    本文涉及到的主要依赖: <dependency> <groupId>org.apache.httpcomponents</groupId> <artifact ...

  5. 基于HttpURLConnection 网络请求工具类的封装

    HttpUtils: /*** Created by xiaoyehai on 2018/5/21 0021.*/public class HttpUtils {//线程池private static ...

  6. HttpClient 发送 HTTP、HTTPS 请求的简单封装

    序 近期这几周.一直在忙同一个项目.刚開始是了解需求.需求有一定了解之后,就開始调第三方的接口.因为第三方给提供的文档非常模糊,在调接口的时候,出了非常多问题,一直在沟通协调,详细的无奈就不说了,因为 ...

  7. 【Java】HTTP请求工具类

    前言 在工作中可能存在要去调用其他项目的接口,这篇文章我们实现在Java代码中实现调用其他项目的接口. 本章内容: 创建一个携带参数的POST请求,去请求其他项目的接口并返回数据. 附加HTTP请求工 ...

  8. Http请求工具类:Get/Post

    第一种 import com.alibaba.fastjson.JSONObject; import org.apache.http.HttpEntity; import org.apache.htt ...

  9. C#实现的UDP收发请求工具类实例

    本文实例讲述了C#实现的UDP收发请求工具类.分享给大家供大家参考,具体如下: 初始化: ListeningPort = int.Parse(ConfigurationManager.AppSetti ...

最新文章

  1. ansible自动化运维(三)——Playbook实战
  2. 爬虫实战:Requests+BeautifulSoup 爬取京东内衣信息并导入表格(python)
  3. php插入成功数据不显示,PHP插入数据不成功,什么原因呢?
  4. JD商家后台管理的细节
  5. (百万浏览量!)超详细MySQL安装及基本使用教程(史上最详细)
  6. 产品经理欲哭无泪的瞬间2(太真实了)
  7. 作者:牛新(1983-),男,博士,国防科学技术大学并行与分布处理重点实验室助理研究员...
  8. Elementui 自定义loading
  9. BOSS直聘:2020一季度平均招聘薪资8609元 同比增长2.8%
  10. mysql 统计存在加1_mysql 假设存在id则设数据自添加1 ,不存在则加入。java月份计算比較...
  11. IT民工系列——c#操作开心网001,实现几乎所有SNS操作!
  12. 语音识别维特比解码_一种基于维特比算法的花洒语音识别系统及方法与流程
  13. import关键字的使用
  14. 三菱PlC程序大型项目QCPU+QD77MS16
  15. html中怎么让图片做背景透明背景图片,透明背景图片怎么做?
  16. 一卡通管理系统总体设计
  17. 面经手册 · 第20篇《Thread 线程,状态转换、方法使用、原理分析》
  18. 绿色全要素生产率数据(2004-2017年)
  19. 伟大的micropython smartconfig 配网它来了!!!
  20. kotlin Anko的实际用法

热门文章

  1. 印度首富之女大婚,贫穷限制了我的想象……
  2. Hello IPv6
  3. 【使用注意】文件内容突然消失
  4. HtmlUnit优秀文章
  5. 1185 城市名排序
  6. C语言用递归求斐波那契数,让你发现递归的缺陷和效率瓶颈
  7. 用C++11的std::async代替线程的创建
  8. OpenGL渲染管线,着色器,光栅化等概念理解
  9. OpenTSDB 安装
  10. ubuntu16.04安装PCL