TransferEncoding.java是chunked编码解码实现java代码
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.zip.GZIPInputStream;
public class TransferEncoding {
private static String encoding = "UTF-8";
public static void main(String[] args) {
try {
Socket socket = new Socket(InetAddress.getByName("www.iteye.com"), 80);
socket.setSoTimeout(10000); // 10秒钟超时。
OutputStreamWriter osw = new OutputStreamWriter(socket.getOutputStream());
StringBuffer sb = new StringBuffer();
sb.append("GET / HTTP/1.1\r\n");
sb.append("Accept: image/png, image/svg+xml, image/*;q=0.8, */*;q=0.5\r\n");
sb.append("X-HttpWatch-RID: 18613-10702\r\n");
sb.append("Referer: http://www.cnblogs.com/haitao-fan/archive/2013/01/18/2866994.html\r\n");
sb.append("Accept-Language: zh-CN\r\n");
sb.append("User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko\r\n");
sb.append("Accept-Encoding: gzip, deflate\r\n");
sb.append("Host: www.iteye.com\r\n");
sb.append("Connection: Keep-Alive\r\n");
sb.append("DNT: 1\r\n");
//注,这是关键的关键,忘了这里让我搞了半个小时。这里一定要一个回车换行,表示消息头完,不然服务器会等待
sb.append("\r\n");
osw.write(sb.toString());
osw.flush();
//--输出服务器传回的消息的头信息
InputStream is = socket.getInputStream();
boolean isGzip = false;
// 读取所有服务器发送过来的请求参数头部信息
String header = readHeader(is);
System.out.println(header);
// 返回的数据类型,是否是gzip压缩的格式
String acceptEncoding = getHeaderValue(header, "Content-Encoding");
if (acceptEncoding.startsWith("gzip")) {
isGzip = true;