HTTP post和get请求的实现

本文使用HttpClient包实现了HTTP的post和get请求。

· POST

public static String httpPost(String url, String body, Map headers) throws Exception {
        CloseableHttpClient client = HttpClients.createDefault();
        String strResult = null;
        HttpPost method = new HttpPost(url);

        if (null != body) {
            StringEntity entity = new StringEntity(body, "UTF-8");
            entity.setContentEncoding("UTF-8");
            entity.setContentType("application/json");
            method.setEntity(entity);
        }

        if (null != headers) {
            headers.forEach((k, v) -> method.addHeader(k, v));
        }

        HttpResponse result = client.execute(method);
        url = URLDecoder.decode(url, "UTF-8");

        if (result.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            strResult = EntityUtils.toString(result.getEntity());
        }
        return strResult;
    }

· GET

public static String httpGet(String url, Map headers) throws Exception {
        String strResult = null;
        CloseableHttpClient client = HttpClients.createDefault();
        HttpGet request = new HttpGet(url);
        
        if (null != headers) { 
            headers.forEach((k, v) -> request.addHeader(k, v));
        }
        
        HttpResponse response = client.execute(request);
        url = URLDecoder.decode(url, "UTF-8");
        
        if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
            strResult = EntityUtils.toString(response.getEntity());
        }
        return strResult;
    }

你可能感兴趣的:(HTTP post和get请求的实现)