Apache 4.x HttpClient

public static Map callRequest(String requestUrl, Method method, Map<String, String> data) throws IOException {

    CloseableHttpResponse response;

    try {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        for(String key: data.keySet()) {
            nvps.add(new BasicNameValuePair(key, data.get(key)));
        }
        switch (method){
            case GET:{
                HttpGet httpGet = new HttpGet(requestUrl+"&"+ EntityUtils.toString(new UrlEncodedFormEntity(nvps, Consts.UTF_8)));
                response = httpclient.execute(httpGet);
                return parseResponse(response);
            }
            case DELETE:{
                response = httpclient.execute(new HttpDelete(requestUrl));
                return parseResponse(response);
            }
            case PUT:{
                HttpPut httpPut = new HttpPut(requestUrl);
                httpPut.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
                response = httpclient.execute(httpPut);
                return parseResponse(response);
            }
            case POST:{
                String post = Http4Client.post(requestUrl, data);
                return doParse(post);
            }
            default:{
                throw new APIException("Unsupport request METHOD");
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
//        finally {
//            httpclient.close();
//        }

    return null;
}
原文地址:https://www.cnblogs.com/slankka/p/9158491.html