response.setHeader() usage

response.setHeader() download Chinese file name garbled problem Collection   1. HTTP message header

(1) General information header

It can be used in the request message or in the response message, but it has nothing to do with the content of the transmitted entity, such as Data, Pragma

主要: Cache-Control , Connection , Data , Pragma , Trailer , Transfer-Encoding , Upgrade

(2) Request header

It is used to transmit additional information to the server in the request message, mainly including the data type acceptable to the client, the compression method, the language, and the information retained on the client computer and the source address of the hyperlink that issued the request.

主要: Accept , Accept-Encoding , Accept-Language , Host ,

(3) Response header

Used to pass additional information to the client in the response message, including the name of the service program, how the client was required to authenticate, the requested resource has been moved to a new address, etc.

Main: Location , Server , WWW-Authenticate (authentication header)

(4) Entity head

It is used as the meta information of the entity content and describes the attributes of the entity content, including the type, length, compression method, last modification time and data validity period of the entity information.

主要: Content-Encoding , Content-Language , Content-Length , Content-Location , Content-Type

(4) Extension head

Main: Refresh, Content-Disposition

2. The role of several main heads

(1) The role of Content-Type

The purpose of this entity header is to let the server tell the browser what file type the data it is sending belongs to.

For example: when the value of Content-Type is set to text/html and text/plain, the former will let the browser parse the received entity content in HTML format, and the latter will let the browser parse it in normal text.

(2) The role of Content-Disposition

When the type of Content-Type is the type to be downloaded, this header will tell the browser the name and type of the file.

When explaining this content, Mr. Zhang also talked about the solution to solve the garbled Chinese file name. What he usually thinks is to use getBytes(), in fact, the file name should be encoded using the email attachment name encoding method, but IE does not support it. In this way (supported by other browsers), use the MimeUtility.encodeWord("Chinese.txt") method of the javax.mail.internet.* package for encoding.

Example of Content-Disposition extension header:

<%@ page pageEncoding="GBK" contentType="text/html;charset=utf-8" import="java.util.*,java.text.*" %>

<%=DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.CHINA).format(new Date())

%>

<%

               response.setHeader("Content-Type","video/x-msvideo");

               response.setHeader("Content-Disposition", "attachment;filename=aaa.doc");

%>

The type specified in Content-Disposition is the extension of the file, and the file type picture in the pop-up download dialog is displayed according to the extension of the file. After clicking Save, the file is named with the value of filename, and the save type is set in Content. shall prevail.

Note: Be sure to set the Content-Type header field before setting the Content-Disposition header field.

(3) The role of the Authorization header

The role of Authorization is that when the client's access is protected by a password, the server will send a 401 status code and a WWW-Authenticate response header, requiring the client to use Authorization to respond.

E.g:

<%@ page pageEncoding="GBK" contentType="text/html;charset=utf-8" import="java.util.*,java.text.*" %>

<%=DateFormat.getDateTimeInstance(DateFormat.SHORT, DateFormat.SHORT, Locale.CHINA).format(new Date())

%>

<%

response.setStatus(401);

response.setHeader("WWW-Authenticate", "Basic realm=/"Tomcat Manager Application/"");

%>

3. How to implement file download

To achieve file download, we just need to set two special corresponding headers, what are they? If the file name contains Chinese, how to solve it?

Two special corresponding headers:

----Content-Type:       application/octet-stream

----Content-Disposition: attachment;filename=aaa.zip

E.g:

response.setContentType("image/jpeg");response.setHeader("Content- Disposition","attachment;filename=Bluehills.jpg");

If there is Chinese in the filename parameter in the file, garbled characters will appear.

Solution:

(1) MimeUtility.encodeWord("Chinese.txt");//The current version of IE is not enough

(2) new String("Chinese".getBytes("GB2312"),"ISO8859- 1");//Actually this is wrong

4. Test and analyze the problem of garbled file names

response.setHeader() download Chinese file name garbled problem

response.setHeader("Content-Disposition", "attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));

The downloaded program has the above sentence. Generally, the name of the file will be displayed correctly on the download prompt box of IE6, whether it is Simplified Chinese or Japanese. However, at that time, the situation of the file name with very long Chinese file name was really not carefully tested. Now after careful testing, it is found that as long as the text exceeds 17 characters, it cannot be downloaded. analyse as below:

1. Through the original method, which is to use URLEncoder to encode first, when there are more than 17 Chinese characters, IE6 cannot download the file. This is a bug in IE, see Microsoft's Knowledge Base article KB816868. The reason may be that when IE processes the Response Header, the length of the header is limited to about 150 bytes. And a Chinese character encoded into UTF-8 is 9 bytes, then 17 characters are 153 bytes, so an error will be reported. And it's not right without the suffix.

2. Solution: Encoding the file name into ISO8859-1 is a valid solution, the code is as follows:

response.setHeader( "Content-Disposition", "attachment;filename=" + new String( fileName.getBytes("gb2312"), "ISO8859-1" ) );

在确保附件文件名都是简体中文字的情况下,那么这个办法确实是最有效的,不用让客户逐个的升级IE。如果台湾同胞用,把gb2312改成big5就行。但现在的系统通常都加入了 国际化的支持,普遍使用UTF-8。如果文件名中又有简体中文字,又有繁体中文,还有日文。那么乱码便产生了。另外,在上Firefox (v1.0-en)下载也是乱码。

三. 参看邮件中的中文附件名的形式,用outlook新建一个带有中文附件的邮件,然后看这个邮件的源代码,找到:

Content-Disposition: attachment;

filename="=?gb2312?B?0MK9qCDOxLG+zsS1tS50eHQ=?="

用这个filename原理上就可以显示中文名附件,但是现在IE并不支持,Firefox是支持的。尝试使用 javamail 的MimeUtility.encode()方法来编码文件名,也就是编码成 =?gb2312?B?xxxxxxxx?= 这样的形式,并从 RFC1522 中找到对应的标准支持。

折中考虑,结合了一、二的方式,代码片断如下:

String fileName = URLEncoder.encode(atta.getFileName(), "UTF-8");

/*

* see http://support.microsoft.com/default.aspx?kbid=816868

*/

if (fileName.length() > 150) {

String guessCharset = xxxx

//根据request的locale 得出可能的编码,中文操作系统通常是gb2312

fileName = new String(atta.getFileName().getBytes(guessCharset), "ISO8859-1");

}

response.setHeader("Content-Disposition", "attachment; filename=" + fileName);

The principle of encoding conversion:

First, set the encoding to GB2312 character encoding in the source program, then convert the source program into bytecode and load it into memory according to Unicode encoding (the bytecodes loaded into memory by java are all Unicode encoding), and then obtain according to GB2312 encoding. The byte array of the Chinese string, and then generate the Unicode string in the form of ISO8859-1 encoding (the 4 bytes at this time become 8 bytes, and the high-order bytes are filled with zeros),

java training Beijing java training java training class java employment training java training institution software training best java training

When transmitting in the network, because the characters in the setHeader method can only be transmitted according to ISO8859-1, at this time, the Unicode characters are converted into the ISO8859-1 encoding and sent to the browser (that is, the zeros filled in the high bits just now are filled Removed), at this time, the characters of the ISO8859-1 code received by the browser can be displayed in Chinese because they conform to the GB2312 encoding.

5. Encoding problems when translating jsp into class

Code block 1 in Notepad:

<%=

       "a中文".length()

%>

Code block 2:

<%@ page pageEncoding="gbk"%>

<%=

       "a中文".length()

%>

Why the output value above is 5, and the output value below is 3?

Because the above code does not add the encoding description of the file, when the WEB application translates the jsp into a class file, the content of the string is calculated according to the encoded ASCII code specified by the default save method. In UTF-8, The original ASCII character occupies one byte, the Chinese character occupies two bytes, corresponding to two characters, the length becomes 5, and the following is the GBK code, one Chinese character and one English correspond to one character, and the result is 3.

]

response.setHeader(...) when there are spaces in the file name

String fileName = StringUtils.trim(file.getName());

String formatFileName = encodingFileName(name);//在后面定义方法encodingFileName(String fileName); response.setHeader("Content-Disposition", "attachment; filename=" + formatFileName );

// handle spaces in filenames  

//Where %20 is the encoding of spaces in UTF-8

public static String encodingFileName(String fileName) {         String returnFileName = "";         try {             returnFileName = URLEncoder.encode(fileName, "UTF-8");             returnFileName = StringUtils.replace(returnFileName, "+", "%20");             if (returnFileName.length() > 150) {                 returnFileName = new String(fileName.getBytes("GB2312"), "ISO8859-1");                 returnFileName = StringUtils.replace(returnFileName, " ", "%20");             }         } catch (UnsupportedEncodingException e) {             e.printStackTrace();             if (log.isWarnEnabled()) {                 log.info("Don't support this encoding ...");             }         }         return returnFileName;     }

 

 

Reprinted to: https://www.cnblogs.com/mingforyou/p/3281945.html    

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324891435&siteId=291194637