发送xml格式的http请求工具类

发送xml格式的http请求

package com.yannis.utils;

import com.google.gson.Gson;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;

public class RestRpcClient {
    private static Log LOG = LogFactory.getLog(RestRpcClient.class);
    private String url;

    public RestRpcClient(String url) {
        this.url = url;
    }

    public String call(Map<String, String> paramMap) {
        try {
            HttpUriRequest request = buildUriRequest(url, paramMap);
            return HttpClients.createDefault().execute(request, new BasicResponseHandler());
        } catch (Exception e) {
            LOG.error("*** HttpClients execute failed due to [" + e.getMessage() + "], url: " + url, e);
        }
        return null;
    }

    public String call(List<NameValuePair> pares) {
        try {
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(pares, HTTP.UTF_8));
            return HttpClients.createDefault().execute(httpPost, new BasicResponseHandler());
        } catch (Exception e) {
            return throwSystemError(e, url);
        }
    }

    public <T> T call(Map<String, String> paramMap, Class<T> typeClass) {
        HttpResponse response = null;
        try {
            HttpUriRequest request = buildUriRequest(url, paramMap);
            response = HttpClients.createDefault().execute(request);
            return resolveRsp(typeClass, response);
        } catch (Exception e) {
            return throwSystemError(e, url);
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    }

    public static <T> T invokeXml(String url, Object rq, Class<T> typeClass) {
        HttpResponse response = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            StringEntity entity = new StringEntity(JaxbMapper.toXml(rq), ContentType.create("application/xml", "UTF-8"));
            httpPost.setEntity(entity);

//            HttpClient instance =
//                    HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
            response = HttpClients.createDefault().execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY){
                response = HttpClients.createDefault().execute(httpPost);
            }
            return resolveRspXml(typeClass, response);
        } catch (Exception e) {
            return throwSystemError(e, url);
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    }

    public static <T> T invokeXmlHtml(String url, Object rq, Class<T> typeClass) {
        HttpResponse response = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            StringEntity entity = new StringEntity(JaxbMapper.toXml(rq), ContentType.create("application/xml", "UTF-8"));
            httpPost.setEntity(entity);

//            HttpClient instance =
//                    HttpClientBuilder.create().setRedirectStrategy(new LaxRedirectStrategy()).build();
            response = HttpClients.createDefault().execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode == HttpStatus.SC_MOVED_PERMANENTLY || statusCode == HttpStatus.SC_MOVED_TEMPORARILY){
                response = HttpClients.createDefault().execute(httpPost);
            }
            return resolveRspXmlHtml(typeClass, response);
        } catch (Exception e) {
            return throwSystemError(e, url);
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    }

    public static <T> T invoke(String url, Object rq, Class<T> typeClass) {
        HttpResponse response = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            StringEntity entity = new StringEntity(new Gson().toJson(rq), ContentType.create("application/json", "UTF-8"));
            httpPost.setEntity(entity);

            response = HttpClients.createDefault().execute(httpPost);
            return resolveRsp(typeClass, response);
        } catch (Exception e) {
            return throwSystemError(e, url);
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    }

    private static <T> T resolveRsp(Class<T> typeClass, HttpResponse response) throws IOException {
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            return new Gson().fromJson(EntityUtils.toString(response.getEntity(), "UTF-8"), typeClass);
        } else {
            throw new RuntimeException("invalid status code: " + statusCode);
        }
    }

    private static <T> T resolveRspXml(Class<T> typeClass, HttpResponse response) throws Exception {
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            return JaxbMapper.fromXml(EntityUtils.toString(response.getEntity(), "UTF-8"), typeClass);
        } else {
            String strResponse = EntityUtils.toString(response.getEntity(), "UTF-8");
            try{
                return JaxbMapper.fromXml(strResponse, typeClass);
            }catch (Exception e){
                // 解析错误不影响主流程
            }
            LOG.error("invalid status code: " + statusCode +  " response:" + strResponse);
            throw new RuntimeException("invalid status code: " + statusCode +  ",response:" + strResponse);
        }
    }
    private static <T> T resolveRspXmlHtml(Class<T> typeClass, HttpResponse response) throws Exception {
        int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode == HttpStatus.SC_OK) {
            String html = EntityUtils.toString(response.getEntity(), "UTF-8");
            return JaxbMapper.fromXml(StringEscapeUtils.unescapeHtml4(html), typeClass);
        } else {
            String html = EntityUtils.toString(response.getEntity(), "UTF-8");
            String strResponse = StringEscapeUtils.unescapeHtml4(html);
            try{
                return JaxbMapper.fromXml(strResponse, typeClass);
            }catch (Exception e){
                // 解析错误不影响主流程
            }
            LOG.error("invalid status code: " + statusCode +  " response:" + strResponse);
            throw new RuntimeException("invalid status code: " + statusCode +  ",response:" + strResponse);
        }
    }
    private static <T> T throwSystemError(Exception e, String url) {
        String error = "*** HttpClients execute failed due to [" + e.getMessage() + "], url: " + url;
        LOG.error(error, e);
        throw new RuntimeException(error);
    }

    @Deprecated
    public <T> T call(Object rq, Class<T> typeClass) {
        HttpResponse response = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            StringEntity entity = new StringEntity(new Gson().toJson(rq), ContentType.create("application/json", "UTF-8"));
//            entity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
            httpPost.setEntity(entity);
            response = HttpClients.createDefault().execute(httpPost);

            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                T rs = new Gson().fromJson(EntityUtils.toString(response.getEntity(), "UTF-8"), typeClass);
                return rs;
            } else {
                throw new RuntimeException("invalid status code: " + statusCode);
            }
        } catch (Exception e) {
            return throwSystemError(e, url);
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    }

    private HttpUriRequest buildUriRequest(String url, Map<String, String> paramMap) {
        RequestBuilder requestBuilder = RequestBuilder.post().setUri(url);
        for (Map.Entry<String, String> e : paramMap.entrySet()) {
            requestBuilder.addParameter(e.getKey(), e.getValue());
        }
        return requestBuilder.build();
    }

    public static <T> T invoke(String url, Object rq, Type successType, Type failureType) {
        HttpResponse response = null;
        try {
            HttpPost httpPost = new HttpPost(url);
            StringEntity entity = new StringEntity(new Gson().toJson(rq), ContentType.create("application/json", "UTF-8"));
            httpPost.setEntity(entity);

            response = HttpClients.createDefault().execute(httpPost);

            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == HttpStatus.SC_OK) {
                return resolveRsp(EntityUtils.toString(response.getEntity(), "UTF-8"), successType, failureType);
            } else {
                throw new RuntimeException("invalid status code: " + statusCode);
            }
        } catch (Exception e) {
            return throwSystemError(e, url);
        } finally {
            HttpClientUtils.closeQuietly(response);
        }
    }

    private static <T> T resolveRsp(String json, Type successType, Type failureType) throws IOException {
        if (json != null && json.contains("success\":true")) {
            return new Gson().fromJson(json, successType);
        } else {
            return new Gson().fromJson(json, failureType);
        }

    }
}

使用

 HotelRoomsResponse hotelRoomsResponse = RestRpcClient.invokeXml(jalanUrlProperties.getRooms(), hotelRoomsRequest, HotelRoomsResponse.class);

请求与响应对象要符合JAXB规范。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

刘彦青-Yannis

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值