Java http GET POST 请求传参

HTTP POST请求传参方式
方式一:

        String url = "http://xxxxxxx";
        logger.info("访问接口url: " + url);

        Map<String, String> paramsMap = new HashMap<>();
        paramsMap.put("name", "小明");
        paramsMap.put("age", 18);
        String paramJson = JSON.toJSONString(paramsMap);
        logger.info("json传参:" + paramJson);


        HttpHeaders headers = new HttpHeaders();
        headers.set("X-Access-token", token);
        logger.info("设置token:" + token);
        headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
        logger.info("设置请求Accept格式:APPLICATION_JSON");
        headers.setContentType(MediaType.APPLICATION_JSON);
         logger.info("设置请求ContentType格式:APPLICATION_JSON");
        HttpEntity<String> request = new HttpEntity<String>(paramJson, headers);

        try {
            restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));

            response = restTemplate.postForEntity(url, request, Map.class);

            map = (Map<String, Object>) response.getBody();
            
            logger.info("获取请求接口返回信息:" + map);

            Map<String, Object> map_data = (Map<String, Object>) map.get("data");
           

方式二

        // 创建HttpClient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //http请求url
        HttpPost httpPost = new HttpPost("http://xxxx");
        // 模拟POST/PUT的body中数据,需转为JSON进行签名.
        Map<String, Object> dataMap = new HashMap<String, Object>();
        //POST请求参数
        //授权码
        dataMap.put("authorizationKey", "");
        //客户端IP
        dataMap.put("clientIp", "");
        //名称
        dataMap.put("name", "");
        //转为json传参
        String bodyParam = new Gson().toJson(dataMap);
        //设置编码
        StringEntity bodyData = new StringEntity(bodyParam, "UTF-8");
        httpPost.setEntity(bodyData);
        try {
            httpPost.setHeader("Content-type", "application/json");
            httpPost.setHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
            String urlStr = httpPost.getURI().toString();
            // 公共参数URL
            httpPost.setURI(new URI(urlStr));
            //请求超时时间
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(5000)
                    .setConnectionRequestTimeout(5000).setSocketTimeout(5000).build();
            httpPost.setConfig(requestConfig);

            // 执行请求
            CloseableHttpResponse response = httpclient.execute(httpPost);
            // 取响应的结果
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                String resp = EntityUtils.toString(response.getEntity());
                //此处不同格式的返回信息 用不通方式的json去转
                //请看 https://blog.csdn.net/weixin_38193704/article/details/127402069?spm=1001.2014.3001.5502
                JSONArray jsonArray = (JSONArray) JSONArray.parse(resp);
                if (ObjectUtils.isNotEmpty(jsonArray)) {
                    JSONObject objectJson = jsonArray.getJSONObject(0);
                   System.out.println("获取返回值json信息" + objectJson);
                }
            }
        } catch (Exception e1) {
            e1.printStackTrace();

        }

HTTP GET请求传参方式

       //请求参数
        String getQueryParam = "USER_ID=" + userId + "&" + "USER_NO=" + userNo + "&" +      "IDCARD_NO=" + idcardNo;
         // 时间戳
        Long ts = Calendar.getInstance().getTime().getTime();
        // 随机数
        String once = RandomStringUtils.randomAlphanumeric(RANDOM_UUID);
        //签名算法
        String signMethod = "SHA-256";
        // 接口header中的公共参数
        String commonParamUrl = String.format("appKey=%s" + "&" + "ts=%s" + "&" + "once=%s" + "&" + "signMethod=%s",
                geerappkey.get(0).getFieldValue(), ts, once, signMethod);
        // 创建HttpClient对象
        CloseableHttpClient httpclient = HttpClients.createDefault();
        //请求的url
        String getFullUrl = serverApiUrl + "?" + queryParam;
        HttpGet httpGet = new HttpGet(getFullUrl);
        //路径添加header信息
        String getAllParamUrl = commonParamUrl + "&" + queryParam;
        try {
            //获取签名数据
            String signData = TokenUtil.getSignature(geerpwd.get(0).getFieldValue(), getAllParamUrl, signMethod);
            log.info("获取请求机构信息签名===" + signData);
            // 添加header参数 appCode、timestamp、 signaturenonce、signature
            httpGet.addHeader("appKey", geerappkey.get(0).getFieldValue());
            httpGet.addHeader("ts", ts.toString());
            httpGet.addHeader("once", once);
            httpGet.addHeader("signMethod", signMethod);
            httpGet.addHeader("signData", signData);
            String urlStr = httpGet.getURI().toString();
            // 公共参数URL
            log.info("get commonParamter:" + urlStr);
            if (StringUtils.endsWith(urlStr, "/")) {
                urlStr = StringUtils.removeEnd(urlStr, "/");
            }
            //请求时间设置
            httpGet.setURI(new URI(urlStr));
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(3000)
                    .setConnectionRequestTimeout(3000).setSocketTimeout(3000).build();
            httpGet.setConfig(requestConfig);
            log.info("urlStr in request:" + httpGet.getURI().toString());
            // 执行请求
            CloseableHttpResponse response = httpclient.execute(httpGet);
            // 取响应的结果
            int statusCode = response.getStatusLine().getStatusCode();
            log.info("response code status:" + statusCode);
            // 打印响应结果
            if (statusCode == HttpStatus.SC_OK) {
                String result = EntityUtils.toString(response.getEntity(), "utf-8");
                JSONObject resultJson = JSON.parseObject(result);
                log.info("checkIdentityParam body:" + resultJson);
                return resultJson;
            }
        } catch (URISyntaxException e) {
            //签名失败
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值