View Javadoc
1   package com.foxinmy.weixin4j.http.message;
2   
3   import java.io.IOException;
4   import java.io.InputStream;
5   
6   import com.foxinmy.weixin4j.http.HttpHeaders;
7   import com.foxinmy.weixin4j.http.HttpResponse;
8   import com.foxinmy.weixin4j.http.MimeType;
9   import com.foxinmy.weixin4j.util.FileUtil;
10  import com.foxinmy.weixin4j.util.RegexUtil;
11  import com.foxinmy.weixin4j.xml.XmlStream;
12  
13  /**
14   * XML 转换
15   * 
16   * @className XmlMessageConverter
17   * @author jinyu
18   * @date Jul 20, 2016
19   * @since JDK 1.6
20   */
21  public class XmlMessageConverter extends AbstractMessageConverter {
22  
23  	public static final XmlMessageConverter GLOBAL = new XmlMessageConverter();
24  
25  	private static final String XML = "xml";
26  	private static final int BRACKET = '<';
27  
28  	public XmlMessageConverter() {
29  		super(MimeType.APPLICATION_XML, MimeType.TEXT_XML, new MimeType("application", "*+xml"));
30  	}
31  	
32  	@Override
33  	public boolean canConvert(Class<?> clazz, HttpResponse response) {
34  		if (!super.canConvert(clazz, response)) {
35  			String disposition = response.getHeaders().getFirst(HttpHeaders.CONTENT_DISPOSITION);
36  			String fileName = RegexUtil.regexFileNameFromContentDispositionHeader(disposition);
37  			return (fileName != null && FileUtil.getFileExtension(fileName).equalsIgnoreCase(XML));
38  		}
39  		return true;
40  	}
41  
42  	@Override
43  	protected boolean supports(Class<?> clazz, byte[] content) {
44  		return BRACKET == content[0];
45  	}
46  
47  	@Override
48  	protected <T> T convertInternal(Class<? extends T> clazz, InputStream body) throws IOException {
49  		return XmlStream.fromXML(body, clazz);
50  	}
51  }