用HttpClient发送xml/map/json等格式的请求报文

一、简介

HttpClient是Apache Jakarta Common下的子项目,用来提供高效的、最新的、功能丰富的支持HTTP协议的客户端编程工具包,并且它支持HTTP协议最新的版本和建议。HttpClient已经应用在很多的项目中,比如Apache Jakarta上很著名的另外两个开源项目Cactus和HTMLUnit都使用了HttpClient。

二、使用方法

使用HttpClient发送请求、接收响应很简单,一般需要如下几步即可。

1. 创建HttpClient对象。

2. 创建请求方法的实例,并指定请求URL。如果需要发送GET请求,创建HttpGet对象;如果需要发送POST请求,创建HttpPost对象。

3. 如果需要发送请求参数,可调用HttpGet、HttpPost共同的setParams(HetpParams params)方法来添加请求参数;对于HttpPost对象而言,也可调用setEntity(HttpEntity entity)方法来设置请求参数。

4. 调用HttpClient对象的execute(HttpUriRequest request)发送请求,该方法返回一个HttpResponse。

5. 调用HttpResponse的getAllHeaders()、getHeaders(String name)等方法可获取服务器的响应头;调用HttpResponse的getEntity()方法可获取HttpEntity对象,该对象包装了服务器的响应内容。程序可通过该对象获取服务器的响应内容。

6. 释放连接。无论执行方法是否成功,都必须释放连接


三、详细讲解

上面已经说了,不管什么格式的请求报文,原理都是一样的,拼接成字符串,用setEntity(HttpEntity entity)方法来设置请求参数

1.post xml格式的请求

public static String postXML(String url,String xmlFileName){
    CloseableHttpClient client = null;
    CloseableHttpResponse resp = null;
    log.info(xmlFileName);
    try{
        HttpPost httpPost = new HttpPost(url);
        httpPost.setHeader("Content-Type", "text/xml; charset=UTF-8");
        client = HttpClients.createDefault();
        StringEntity entityParams = new StringEntity(xmlFileName,"utf-8");
        httpPost.setEntity(entityParams);
        client = HttpClients.createDefault();
        resp = client.execute(httpPost);
        String resultMsg = EntityUtils.toString(resp.getEntity(),"utf-8");
        return resultMsg;
    }catch (Exception e){
        log.info(e.getMessage());
    }finally {
        try {
            if(client!=null){
                client.close();
            }
            if(resp != null){
                resp.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return null;

}

2.post map格式的请求

public static String doPost(String url,Map,String> map,String charset){
    log.info(url+":"+map);
    CloseableHttpClient httpClient = HttpClients.createDefault();
    //配置超时时间
    RequestConfig requestConfig = RequestConfig.custom().
            setConnectTimeout(10000).setConnectionRequestTimeout(10000)
            .setSocketTimeout(10000).setRedirectsEnabled(true).build();

    HttpPost httpPost = new HttpPost(url);
    httpPost.setHeader("content-type","application/x-www-form-urlencoded");
    //设置超时时间
    httpPost.setConfig(requestConfig);
    //装配post请求参数
    List list = new ArrayList();
    for(Map.Entry,String> maps:map.entrySet()){
        list.add(new BasicNameValuePair(maps.getKey(),maps.getValue()));
    }
    try {
        UrlEncodedFormEntity entity = new UrlEncodedFormEntity(list,"UTF-8");
        //设置post求情参数
        httpPost.setEntity(entity);
        HttpResponse httpResponse = httpClient.execute(httpPost);
        String strResult = "";
        if(httpResponse != null){
            System.out.println(httpResponse.getStatusLine().getStatusCode());
            if (httpResponse.getStatusLine().getStatusCode() == 200) {
                strResult = EntityUtils.toString(httpResponse.getEntity());
            } else if (httpResponse.getStatusLine().getStatusCode() == 400) {
                //strResult = "Error Response: " + httpResponse.getStatusLine().toString();
                strResult = EntityUtils.toString(httpResponse.getEntity());
            } else if (httpResponse.getStatusLine().getStatusCode() == 500) {
                //strResult = EntityUtils.toString(httpResponse.getEntity());
                strResult = "Error Response: " + httpResponse.getStatusLine().toString();
            } else {
                strResult = "Error Response: " + httpResponse.getStatusLine().toString();
                //strResult = "Error Response: " + httpResponse.getStatusLine().toString();
            }
        }
        return strResult;
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        try {
            if(httpClient != null){
                httpClient.close(); //释放资源
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return "";
}

3.post json格式的请求

public static String doPostSSL(String apiUrl, Object json) {
    log.info("请求:"+apiUrl+" 参数:"+json.toString());
    CloseableHttpClient httpClient = createSSLClientDefault();
    HttpPost httpPost = new HttpPost(apiUrl);
    CloseableHttpResponse response = null;
    String httpStr = null;
    try {
        StringEntity stringEntity = new StringEntity(json.toString(),"UTF-8");//解决中文乱码问题
        stringEntity.setContentEncoding("UTF-8");
        stringEntity.setContentType("text/xml");
        httpPost.setEntity(stringEntity);
        response = httpClient.execute(httpPost);
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            return null;
        }
        HttpEntity entity = response.getEntity();
        if (entity == null) {
            return null;
        }
        httpStr = EntityUtils.toString(entity, "utf-8");
        return httpStr;
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (response != null) {
            try {
                EntityUtils.consume(response.getEntity());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return "";
}



你可能感兴趣的:(个人笔记)