httpClient实现对webService服务的调用

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_36720650/article/details/88667490
public class HttpClientUtils {
    private Logger logger = LoggerFactory.getLogger(getClass());
    /**
     * 发送form类型数据无附件
     * @param json :请求的json
     * @param url :请求路径
     * @param defCharset :默认编码
     * @return
     * @throws Exception 
     */
    public String postFormForJson(String json, String url, String defCharset) throws Exception {
        if (logger.isDebugEnabled())
            logger.debug("发送报文[{}]", json);
        // 发送报文
        CloseableHttpClient client = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        String resJson = "";
        InputStream inputStream = null;
        CloseableHttpResponse response = null;
        post.addHeader("Content-Type",
                "application/x-www-form-urlencoded;charset=" + defCharset);
        try {
            List<NameValuePair> paramsList = new ArrayList<NameValuePair>();
            //将请求数据转化成map
            Map<String, Object> paramMap= JsonSerializeUtil.json2Map(json);
            if (null != paramMap) {
                Set<String> keys = paramMap.keySet();
                for (String key : keys) {
                    if (StringUtils.isNotBlank(key)) {
                        Object value = paramMap.get(key);
                        paramsList.add(new BasicNameValuePair(key, null == value ? "" : value.toString()));
                    }
                }
            }
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(paramsList);
            post.setEntity(formEntity);
            try {
                response = client.execute(post);
                if(response.getStatusLine().getStatusCode()==200){
                    HttpEntity eneEntity = response.getEntity();
                    if(eneEntity!=null){
                        try {
                            inputStream = eneEntity.getContent();
                            resJson = IOUtils.toString(inputStream, "UTF-8");
                        } finally{
                            inputStream.close();
                        }
                    }
                }
            } finally{
                response.close();
            }
            logger.debug("响应报文[{}]", resJson);
        } catch (Exception e) {
            logger.error("接口调用异常[{}]", e);
            throw new RuntimeException(e.getMessage());
        } finally {
            client.close();
        }
        return resJson;
    }
    
    /**
     * post发送json实体获取服务端获取响应
     * @param jsonBody :请求的实体
     * @param ur :请求路径
     * @param defCharset :默认编码
     * @return
     * @throws Exception 
     */
    public String postBodyForJson(String jsonBody, String url, String defCharset)
            throws Exception {
        if (logger.isDebugEnabled())
            logger.debug("发送报文[{}]", jsonBody);
        CloseableHttpClient client = HttpClients.createDefault();
        String respContent = "";
        InputStream inputStream = null;
        CloseableHttpResponse resp = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            StringEntity entity = new StringEntity(jsonBody, defCharset);
            httpPost.setEntity(entity);
            httpPost.addHeader("Content-Type", "application/json;charset="
                    + defCharset);
            try {
                resp = client.execute(httpPost);
                if (resp.getStatusLine().getStatusCode() == 200) {
                    HttpEntity he = resp.getEntity();
                    if (he != null) {
                        try {
                            inputStream = he.getContent();
                            respContent = IOUtils
                                    .toString(inputStream, "UTF-8");
                        } finally {
                            inputStream.close();
                        }
                    }
                }
            } finally {
                resp.close();
            }
            logger.debug("响应报文[{}]", respContent);
        } catch (Exception e) {
            logger.error("接口调用异常[{}]", e);
            throw new RuntimeException();
        } finally {
            client.close();
        }
        return respContent;
    }
    
    /**
     * 发送带有query的get的请求
     * 
     * @param json : 请求的json
     * @param url : 请求的路径
     * @param defCharset : 默认编码
     * @return
     * @throws Exception 
     */
    public String getQueryForJson(String json, String url,
            String defCharset) throws Exception {
        if (logger.isDebugEnabled())
            logger.debug("发送报文[{}]", json);
        // 发送报文
        CloseableHttpClient client = HttpClients.createDefault();
        URIBuilder uri = new URIBuilder(url);
        CloseableHttpResponse response = null;
        InputStream in = null;
        String resJson = "";
        try {
            Map<String, Object> paramMap = JsonSerializeUtil.json2Map(json);
            if (null != paramMap) {
                Set<String> keys = paramMap.keySet();
                for (String key : keys) {
                    if (StringUtils.isNotBlank(key)) {
                        Object value = paramMap.get(key);
                        uri.addParameter(key,
                                null == value ? "" : value.toString());
                    }
                }
                if (logger.isDebugEnabled())
                    logger.debug("get请求:[{}]", uri.build().toString());
            }
            HttpGet get = new HttpGet(uri.build());
            response = client.execute(get);
            try {
                if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity eneEntity = response.getEntity();
                    if (eneEntity != null) {
                        try {
                            in = eneEntity.getContent();
                            resJson = IOUtils.toString(in, defCharset);
                        } finally {
                            in.close();
                        }
                    }
                }
            } finally {
                response.close();
            }
            if (logger.isDebugEnabled())
                logger.debug("响应报文[{}]", resJson);
        } catch (Exception e) {
            logger.error("交易报文异常[{}]", e);
            throw new RuntimeException(e.getMessage());
        } finally {
            client.close();
        }
        return resJson;
    }

    
    
    /**
     * 发送带header的HTTP请求post
     * @param headers :头部信息
     * @param charset :编码
     * @param requestJson :请求的json
     * @param url : 请求路径
     * @return
     * @throws Exception 
     */
    @SuppressWarnings("unchecked")
    public String postHeaderForJson(Map<?, ?> Headers, String charset,
            String requestJson, String url) throws Exception {
        String rst = "";
        CloseableHttpResponse response = null;
        InputStream in = null;
        logger.info("发送报文[{}]", requestJson);
        // 发送报文
        CloseableHttpClient client = HttpClients.createDefault();
        try {
            HttpPost post = new HttpPost(url);
            if (Headers != null && Headers.get("headers") != null) {
                Map<String, String> headers = (Map<String, String>) Headers
                        .get("headers");
                Set<String> keys = headers.keySet();
                for (String key : keys) {
                    if (StringUtils.isNotBlank(key)
                            && StringUtils.isNotBlank(headers.get(key))) {
                        String value = headers.get(key);
                        logger.info("发送报文请求headers的key:[{}],value:[{}]", key,
                                value);
                        post.addHeader(key, value);
                    }
                }
            }
            StringEntity entity = new StringEntity(requestJson, charset);
            post.addHeader("Content-Type","application/json;charset="+charset);
            post.setEntity(entity);
            try {
                response = client.execute(post);
                if (response.getStatusLine().getStatusCode() == 200) {
                    HttpEntity entity2 = response.getEntity();
                    if (entity2 != null) {
                        try {
                            in = entity2.getContent();
                            rst = IOUtils.toString(in, charset);
                        } finally {
                            in.close();
                        }
                    }
                }
            } finally {
                response.close();
            }
            logger.debug("响应报文[{}]", rst);
        } catch (Exception e) {
            logger.error("接口调用异常[{}]", e);
            throw new RuntimeException(e.getMessage());
        } finally {
            client.close();
        }
        return rst;
    }
    
    /**
     *  发送带有File附件的post请求
     *  @param filekey:文件的键值
     *  @param file:文件
     *  @param requestJson:请求json数据
     *  @param url:请求的url
     *  @param charset:编码
     */ 
    public CloseableHttpResponse postPartForResponse(String fileKey,File file, String requestJson, String url,String charset){
        CloseableHttpResponse response = null;
        logger.info("发送报文[{}]", requestJson);
        // 发送报文
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpPost post = new HttpPost(url);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        FileBody fileBody = new FileBody(file);
        try {
            //设置map中其他参数
            Map<String, Object> paramMap = JsonSerializeUtil.json2Map(requestJson);
            if (null != paramMap) {
                Set<String> keys = paramMap.keySet();
                for (String key : keys) {
                    if (StringUtils.isNotBlank(key)) {
                        Object value = paramMap.get(key);
                        builder.addPart(key, new StringBody(null == value ? "" : value.toString(), ContentType.TEXT_PLAIN));
                    }
                }
            }
            builder.addPart(fileKey, fileBody);    
            builder.setContentType(ContentType.MULTIPART_FORM_DATA);
            builder.setCharset(Charset.forName(charset));
            HttpEntity entity = builder.build();
            post.setEntity(entity);
            response = httpClient.execute(post);
        }catch (Exception e) {
            logger.error("交易报文编码异常[{}]", e);
            throw new RuntimeException(e.getMessage());
        } finally {
            post.releaseConnection();
        }
        return response;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_36720650/article/details/88667490