java使用HttpClient实现HTTP协议中GET和POST方法

302 阅读1分钟
public class OKHttpUtil {

    /**
     * 发起get请求
     *
     * @param url 请求地址
     * @param headerMap 请求头
     * @return
     */
    public static String httpGet(String url,Map<String, Object> headerMap) {
        String result = null;
        HttpClient httpClient = new DefaultHttpClient();
        try {

            HttpGet httpGet = new HttpGet(url);
            if (headerMap != null) {
                for (String key : headerMap.keySet()) {
                   httpGet.addHeader(key,headerMap.get(key).toString());
                }
            }
            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            result = EntityUtils.toString(httpEntity, "UTF-8");
            EntityUtils.consume(httpEntity);
        } catch (ClientProtocolException e) {
            log.error(e.getMessage());
        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
        return result;
    }

    /**
     * 发送httppost请求
     *
     * @param url 请求地址
     * @param data 提交的参数为json的形式
     * @return
     */
    public static String httpPost(String url, String data,Map<String, Object> headerMap) {

        String result = null;
        HttpClient httpClient = new DefaultHttpClient();

        try {
            HttpPost httpPost = new HttpPost(url);
            if (headerMap != null) {
                for (String key : headerMap.keySet()) {
                    httpPost.addHeader(key, headerMap.get(key).toString());
                }
            }
            httpPost.setEntity(new StringEntity(data, "UTF-8"));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            result = EntityUtils.toString(httpEntity);
            EntityUtils.consume(httpEntity);
        } catch (ClientProtocolException e) {
            log.error(e.getMessage());
        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
        return result;
    }

    /**
     * 发送httppost请求
     *
     * @param url 请求地址
     * @param data 提交的参数为key=value&key1=value1(application/x-www-form-urlencoded; charset=utf-8)的形式
     * @return
     */
    public static String httpPost(String url, Map<String,Object> data, Map<String, Object> headerMap) {

        String result = null;
        HttpClient httpClient = new DefaultHttpClient();

        try {
            HttpPost httpPost = new HttpPost(url);
            if (headerMap != null) {
                for (String key : headerMap.keySet()) {
                    httpPost.addHeader(key, headerMap.get(key).toString());
                }
            }
            httpPost.setEntity(new UrlEncodedFormEntity(getDateStr(data), "UTF-8"));
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            result = EntityUtils.toString(httpEntity);
            EntityUtils.consume(httpEntity);
        } catch (ClientProtocolException e) {
            log.error(e.getMessage());
        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            httpClient.getConnectionManager().shutdown();
        }
        return result;
    }

    /**
     * map参数格式转化 List<NameValuePair>
     * @param parameterMap
     * @return
     */
    private static List<NameValuePair> getDateStr(Map<String,Object> parameterMap){
        List<NameValuePair> nameValuePairs = new ArrayList<>();
        if (parameterMap.size() != 0) {
            // 将mapdata中的key存在set集合中,通过迭代器取出所有的key,再获取每一个键对应的值
            Set keySet = parameterMap.keySet();
            Iterator it = keySet.iterator();
            while (it.hasNext()) {
                String k =  it.next().toString();// key
                String v = parameterMap.get(k).toString();// value
                nameValuePairs.add(new BasicNameValuePair(k, v));
            }
        }
        return nameValuePairs;
    }

}