Java tutorial
/* * @(#)HttpResponse 1.0 2015-01-05 * * Copyright 2009 chinabank payment All Rights Reserved. * PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * Author Email: yfchenyun@jd.com */ package org.thorn.emma.model; import org.apache.commons.lang3.StringUtils; import org.thorn.emma.util.CharsetDetector; import java.io.UnsupportedEncodingException; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * http??. * * @author chenyun313@gmail.com, 2015-01-05. * @version 1.0 * @since 1.0 */ public class HttpResponse { private String requestUrl; private int statusCode; private Map<String, List<String>> headers = new HashMap<String, List<String>>(); private byte[] content; private String charset; private String contentType; private String fileSuffix; public HttpResponse(String requestUrl) { this.requestUrl = requestUrl; } public String getRequestUrl() { return requestUrl; } public int getStatusCode() { return statusCode; } public void setStatusCode(int statusCode) { this.statusCode = statusCode; } public Map<String, List<String>> getHeaders() { return headers; } public void setHeaders(Map<String, List<String>> headers) { this.headers = headers; List<String> contentType = headers.get("Content-Type"); if (contentType != null) { String ct = StringUtils.remove(contentType.get(0), " "); Pattern p = Pattern.compile("(\\w+[-]*\\w*)/(\\w+[-]*\\w*)(;charset=)?(.*)", Pattern.CASE_INSENSITIVE); Matcher matcher = p.matcher(ct); if (matcher.find()) { this.contentType = matcher.group(1); this.fileSuffix = matcher.group(2); this.charset = matcher.group(4); if (StringUtils.equalsIgnoreCase(this.contentType, "text") && StringUtils.isEmpty(this.charset)) { // ????, ?byte charset = CharsetDetector.guessEncoding(content); } } } } public byte[] getContent() { return content; } public void setContent(byte[] content) { this.content = content; } public Set<String> getNewCookie() { List<String> setCookie = headers.get("Set-Cookie"); Set<String> newCookie = new HashSet<String>(); if (setCookie != null) { for (String cookie : setCookie) { String[] array = StringUtils.split(cookie, ";"); for (String str : array) { str = str.trim(); if (StringUtils.startsWithIgnoreCase(str, "path") || StringUtils.startsWithIgnoreCase(str, "domain")) { continue; } newCookie.add(str); } } } return newCookie; } public String getContentType() { return this.contentType; } public String getHtml() throws UnsupportedEncodingException { String encode = getContentType(); return new String(this.content, encode); } public String getCharset() { return charset; } public String getFileSuffix() { return fileSuffix; } }