图解springboot后端发送HttpGet和HttpPost请求

图解springboot后端发送HttpGet和HttpPost请求

[提前声明]
文章由作者:张耀峰 结合自己生产中的使用经验整理,最终形成简单易懂的文章
写作不易,转载请注明,谢谢!
代码案例地址: ?https://github.com/Mydreamandreality/sparkResearch


注:此篇文章中使用的方式已经不推荐使用了、因为使用过于繁琐、可以参考最新的文章

点击跳转、SpringBoot发送Http请求-RestTemplate

图解springboot后端发送HttpGet和HttpPost请求

我们要实现的功能如下:
SpringBoot后端请求get和post接口,并且携带请求参数,对返回的JSON进行解析


我本地的开发环境是:SpringBoot2.1,发起请求的工具是:Apache,Http.client

一: HttpPost请求,提交JSON参数,且解析返回的JSON案例

完整代码案例:

    @Scheduled(cron = Settings.cron)
    public void getUpdateAsset() {
        Long milliSecond = LocalDateTime.now().toInstant(ZoneOffset.of("+8")).toEpochMilli() - 300000;
        String jsonParam = " { \"update\" : " + milliSecond + "}";
        
        String headersAuthor = sendPostUrlGetLoginToken("operator");
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        CloseableHttpResponse closeableHttpResponse;
        
        try {
            HttpPost httpPost = new HttpPost(updateAssetUrl);
            httpPost.setHeader("Authorization", "Bearer " + headersAuthor);
            httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");
            StringEntity entity = new StringEntity(jsonParam, ContentType.create("text/json", "UTF-8"));
            httpPost.setEntity(entity);
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
            httpPost.setConfig(requestConfig);
            
            closeableHttpResponse = closeableHttpClient.execute(httpPost);

            int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                //TODO:状态码非200代表没有正常返回,此处处理你的业务
            }

            HttpEntity httpEntity = closeableHttpResponse.getEntity();
            String asset_synchronization = EntityUtils.toString(httpEntity, "UTF-8");
            JSONArray jsonArray = JSONArray.parseArray(asset_synchronization);
            if (jsonArray.size() > 0) {
                //TODO:判断返回的json数组是否不为空,此处即可处理你的业务
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
图解HttpPost请求代码案例:

图解springboot后端发送HttpGet和HttpPost请求_第1张图片
图解springboot后端发送HttpGet和HttpPost请求_第2张图片

  • 在第一步,首先生成我们需要提交的参数,sendPostUrlGetLoginToken是我获取参数的方法,无需关注
  • 在第二步,我们新建Http的client客户端,并且生成HttpPost请求方式,此处如果post请求发送body的json参数,需要指定httpPost.addHeader("Content-Type", "application/json;charset=UTF-8");,通过setEntity()把我们要提交的json参数写入post请求
  • 在第三步,执行httpPost请求,并且获取接口返回的状态码,此处我的需求是:非200的状态码一律抛出token失效异常,你们可以根据自己的需求开发
  • 第四步,就是最后一步,是处理200正常状态码的代码块,通过getEntity()获取接口返回给我的json数据,进行解析,200的code码如何处理和数据如何解析看自己的业务决定


二: HttpGet请求,提交Params参数,且解析返回的JSON案例

完整代码案例:

    public String sendPostUrlGetLoginToken(String username) {
    //此处是我获取请求参数的方法,请忽略
        String[] author = authorApi();
        List nameValuePairs = new LinkedList<>();
        nameValuePairs.add(new BasicNameValuePair("username", "operator"));
        nameValuePairs.add(new BasicNameValuePair("timestamp", author[0]));
        nameValuePairs.add(new BasicNameValuePair("nonce", author[1]));
        nameValuePairs.add(new BasicNameValuePair("signature", author[2]));
        CloseableHttpClient closeableHttpClient = HttpClients.createDefault();
        CloseableHttpResponse closeableHttpResponse;
        String paramStr;
        try {
            paramStr = EntityUtils.toString(new UrlEncodedFormEntity(nameValuePairs));
            HttpPost httpPost = new HttpPost(appendString(tokenUrl, paramStr));
            RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(2000).setConnectTimeout(2000).build();
            httpPost.setConfig(requestConfig);
            //sendPostURL.
            closeableHttpResponse = closeableHttpClient.execute(httpPost);
            //HttpCode
            int statusCode = closeableHttpResponse.getStatusLine().getStatusCode();
            if (statusCode != HttpStatus.SC_OK) {
                throw new GunsException(BizExceptionEnum.TOKEN_ERROR);
            }
            //此处处理状态码200
            HttpEntity httpEntity = closeableHttpResponse.getEntity();
            String isLogin = EntityUtils.toString(httpEntity, "UTF-8");
            return isLogin.substring(1, isLogin.length() - 1);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    
        
        /**
        * 把请求参数通过?拼接
        * 示例: 1.1.1.1:80/?uname=1&token=1
        */
        public String appendString(String url, String paramStr) {
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append(url);
        stringBuffer.append("?");
        stringBuffer.append(paramStr);
        return stringBuffer.toString();
    }

图解HttpGet请求案例:

图解springboot后端发送HttpGet和HttpPost请求_第3张图片
图解springboot后端发送HttpGet和HttpPost请求_第4张图片

  • 其实代码的思路和HttpPost的请求时一致的,只是我们在提交param参数时,需要写入List,还是提交请求,并且判断状态码,接着通过状态码实现自己的业务

有任何问题可以留言交流,我看到会第一时间回复

你可能感兴趣的:(一文读懂系列,springboot干货,Java后端)