zoukankan      html  css  js  c++  java
  • Java 网络请求

    直接上代码:

    public class HttpUtils {
    
        private static final RestTemplate restTemplate = new RestTemplate();
    
        // Get请求
        public static String Get(String url, Map<String, Object> params) {
            String uri = buildUri(url, params);
            ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class);
            return response.getBody();
        }
    
        // Get请求
        public static String Get(String uri) {
            ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class);
            return response.getBody();
        }
    
        // Post请求(JSON请求)
        public static String JPost(String url, Map<String, Object> params) {
            HttpEntity<Map<String, Object>> request = new HttpEntity<>(params, jsonHeaderBuilder());
            ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
            return response.getBody();
        }// Post请求(Params)
        public static String UPost(String url, MultiValueMap<String, String> params) {
            HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(params, urlHeaderBuilder());
            ResponseEntity<String> response = restTemplate.postForEntity(url, request, String.class);
            return response.getBody();
        }
    
        // 拼接Url和参数
        private static String buildUri(String url, Map<String, Object> params) {
            StringBuilder sb = new StringBuilder(url);
            sb.append("?");
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            sb.deleteCharAt(sb.length() - 1);
            return sb.toString();
        }
    
        // 构建Url请求头
        private static HttpHeaders urlHeaderBuilder() {
            HttpHeaders h = new HttpHeaders();
            h.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            return h;
        }
    
        // 构建Json请求头
        private static HttpHeaders jsonHeaderBuilder() {
            HttpHeaders h = new HttpHeaders();
            h.setContentType(MediaType.APPLICATION_JSON);
            return h;
        }
    
    }
    知止而后有定;定而后能静;静而后能安;安而后能虑;虑而后能得。
  • 相关阅读:
    jquery 代码搜集
    Windows Server 2008中安装IIS7.0
    javascript 判断两个日期之间的天数 兼容ie,firefox
    jquery选择器大全
    原始ajax方式调用asp.net后台方法
    JavaScript及C# URI编码详解
    利用JQuery直接调用asp.net后台方法
    C#操作XML小结_转载
    从bnbt tracker源码分析bt客户端与traker的通信
    传说中的神器: shared_ptr/weak_ptr/scoped_ptr
  • 原文地址:https://www.cnblogs.com/SamNicole1809/p/15413434.html
Copyright © 2011-2022 走看看