发送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);}@Deprecatedpublic <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规范。