• 使用Java调用RestFul接口的几种方法


    使用Java调用RestFul接口的几种方法

    1. HttpURLConnection

    public String postRequest(String url, String param) {
        StringBuffer result = new StringBuffer();
    
        HttpURLConnection conn = null;
        OutputStream out = null;
        BufferedReader reader = null;
        try {
            URL restUrl = new URL(url);
            conn = (HttpURLConnection) restUrl.openConnection();
            conn.setRequestMethod("POST");
            conn.setDoOutput(true);
            conn.setDoInput(true);
    
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            conn.setRequestProperty("Content-Type", "application/json; charset=utf-8");
    
            conn.connect();
            out = conn.getOutputStream();
            out.write(param.getBytes());
            out.flush();
    
            int responseCode = conn.getResponseCode();
            if(responseCode != 200){
                throw new RuntimeException("Error responseCode:" + responseCode);
            }
    
            String output = null;
            reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
            while((output=reader.readLine()) != null){
                result.append(output);
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("调用接口出错:param+"+param);
        } finally {
            try {
                if(reader != null){
                    reader.close();
                }
                if(out != null){
                    out.close();
                }
                if(conn != null){
                    conn.disconnect();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
    
        return result.toString();
    }

    2. HttpClient方式

    public class HttpClientUtil {
    
        public String post(String url, Map<String, Object> pramMap) throws Exception {
            String result = null;
            // DefaultHttpClient已过时,使用CloseableHttpClient替代
            CloseableHttpClient closeableHttpClient = null;
            CloseableHttpResponse response = null;
            try {
                closeableHttpClient = HttpClients.createDefault();
                HttpPost postRequest = new HttpPost(url);
                List<NameValuePair> pairs = new ArrayList<>();
                if(pramMap!=null && pramMap.size() > 0){
                    for (Map.Entry<String, Object> entry : pramMap.entrySet()) {
                        pairs.add(new BasicNameValuePair(entry.getKey(), String.valueOf(entry.getValue())));
                    }
                }
                UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(pairs, "utf-8");
                postRequest.setEntity(formEntity);
    
                response = closeableHttpClient.execute(postRequest);
                if(response!=null && response.getStatusLine().getStatusCode()==HttpStatus.SC_OK){
                    result = EntityUtils.toString(response.getEntity(), "utf-8");
                }else{
                    throw new Exception("post请求失败,url" + url);
                }
    
            } catch (Exception e) {
                e.printStackTrace();
                throw e;
            } finally {
                try {
                    if(response != null){
                        response.close();
                    }
                    if(closeableHttpClient != null){
                        closeableHttpClient.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
    
            return result;
        }
    
    }

    3.  spring提供的RestTemplate模板方式

    public class RestTemplateUtil {
     
        @Bean
        public RestTemplate restTemplate(){
            RestTemplate template = new RestTemplate();
            // messageConverters是RestTemplate的一个final修饰的List类型的成员变量
            // messageConverters的第二个元素存储的是StringHttpMessageConverter类型的消息转换器
            // StringHttpMessageConverter的默认字符集是ISO-8859-1,在此处设置utf-8字符集避免产生乱码
            template.getMessageConverters().set(1, new StringHttpMessageConverter(Charset.forName("utf-8")));
            return template;
        }
     
        @Autowired
        private RestTemplate restTemplate;
     
        public String post(String url, String jsonParam){
            // 自定义请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.setAcceptCharset(Collections.singletonList(Charset.forName("utf-8")));
            headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
     
            // 参数
            HttpEntity<String> entity = new HttpEntity<String>(jsonParam, headers);
            // POST方式请求
            ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
            if(responseEntity == null){
                return null;
            }
     
            return responseEntity.getBody().toString();
        }
     
    }

    Reference

    https://www.cnblogs.com/liuyb/p/11202004.html

    https://www.cnblogs.com/lukelook/p/11169219.html

    https://blog.csdn.net/weixin_44219219/article/details/115762270

    https://www.cnblogs.com/super-jing/p/10794564.html

    https://blog.csdn.net/u010916254/article/details/88915534

    https://blog.csdn.net/s906199800/article/details/83379437

    https://cloud.tencent.com/developer/article/1645594

    https://juejin.cn/post/7052900785381703694

    https://blog.csdn.net/loy_184548/article/details/80003581

  • 相关阅读:
    C++11:22委托构造函数和继承构造函数
    C++11:21通过智能指针管理第三方库分配的内存
    python 常识
    计算机基础
    XML
    flask请求上下文 及相关源码
    Flask框架
    Django orm 常用字段和参数
    docker 使用
    视图家族
  • 原文地址:https://www.cnblogs.com/pugang/p/16773181.html
Copyright © 2020-2023  润新知