java代码发送http请求

业务场景: 请求第三方接口,注意事项就是对方和己方服务开墙问题

方式一: 采用restTemplate

自定义设置连接超时和请求超时,然后具体代码实现

    @Bean
    public RestTemplate getRestTemplate(){
        SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
        /**
         * 读写超时自定义
         */
        requestFactory.setConnectTimeout(3*1000);
        requestFactory.setReadTimeout(5 * 1000);
        return new RestTemplate(requestFactory);
    }
    @Autowired
    private RestTemplate restTemplate;
    
    @RequestMapping(value = "getResult")
    public String getResult(){
        String url = ""; //请求url,参数如果放在url后,可以通过StringBuilder进行拼接
        HashMap<String, Object> map = new HashMap<>();
        try {
            String param = new GsonBuilder().create().toJson(map);
            RequestEntity<String> requestEntity = RequestEntity.post(new URI(url)).contentType(MediaType.APPLICATION_JSON).body(param);
            ResponseEntity<String> exchange = restTemplate.exchange(requestEntity, String.class);
            /**
             * 返回请求结果,若遇到中文乱码转换一下
             */
            String body = exchange.getBody();
            if (body != null) {
                String s = new String(body.getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8);
                /**
                 * 其他进行数据解析操作
                 */
                UserInfo userInfo = new GsonBuilder().create().fromJson(s, UserInfo.class);
                
            }


        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        return "ok";
    }

 

 

 

方式二,采用apache工具类中

 

1.依赖pom文件,使用的apache的httpClient

2.撸代码,设置请求头

    public static String httpRequest(String url, String jsonParam, Map<String, String> headerMap) {
        HttpPost httpPost = new HttpPost();
        URI uri = null;
        try {
            uri = new URIBuilder(url).build();
        } catch (URISyntaxException e) {
            e.printStackTrace();
        }
        httpPost.setURI(uri);
        httpPost.setHeader("Content-Type", "application/json;charset=utf-8");
        /**
         * 设置额外的头信息
         */
        if (headerMap != null && !headerMap.isEmpty())
            for (Map.Entry<String, String> entry : headerMap.entrySet()) {
                if (StringUtils.isEmpty(entry.getKey()) || StringUtils.isEmpty(entry.getValue())) {
                    continue;
                }
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }

        StringEntity entity = null;
        try {
            entity = new StringEntity(jsonParam);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json;charset=utf-8");
        httpPost.setEntity(entity);

        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        long startTime = System.currentTimeMillis();
        try {
            response = httpClient.execute(httpPost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        long startEnd = System.currentTimeMillis();
        log.info("查询耗时:{} ms", (startEnd - startTime));
        //请求时间
        String resultStr = null;
        if (response != null) {
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            log.info("查询状态码:{}", statusCode);
            // 打印状态码
            if (statusCode == 200) {
                HttpEntity responseEntity = response.getEntity();
                try {
                    resultStr = EntityUtils.toString(responseEntity, "UTF-8");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } else {
            //异常
        }

        if (httpClient != null) {
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        if (response != null) {
            try {
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return resultStr;
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值