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;
}
posted @ 2017-04-10 16:32  一杯半盏  阅读(114)  评论(0编辑  收藏  举报