美文网首页
HTTP post和get请求的实现

HTTP post和get请求的实现

作者: Jiu_Ming | 来源:发表于2018-06-06 11:20 被阅读0次

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

· POST

public static String httpPost(String url, String body, Map<String, String> 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<String, String> 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请求的实现

      本文链接:https://www.haomeiwen.com/subject/ekcbsftx.html