Java教程

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;
    }

}

 

这篇关于Java 网络请求的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!