62,614
社区成员
发帖
与我相关
我的任务
分享
public static void main(String[] args) throws IOException {
URL url = new URL("http://www.gome.com.cn/ec/homeus/browse/provinceDroplet.jsp?callback=g");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.connect();
InputStream in = connection.getInputStream();
GZIPInputStream gzip = new GZIPInputStream(in);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n;
while ((n = gzip.read(buf)) != -1) {
baos.write(buf, 0, n);
}
String content = new String(baos.toByteArray(), "UTF-8");
System.out.println(content);
connection.disconnect();
}
public static void main(String[] args) throws Exception {
httpRequestTest();
}
public static String readLine(InputStream in, String charset)
throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int b;
while ((b = in.read()) != -1 && b != 0x0D) {
baos.write(b);
}
if (b != -1) {
in.read(); // should always be 0x0A
}
return new String(baos.toByteArray(), charset);
}
public static void httpRequestTest() throws IOException {
StringBuilder sb = new StringBuilder();
sb.append("GET /ec/homeus/browse/provinceDroplet.jsp?callback=g HTTP/1.1\r\n");
sb.append("Accept: */*\r\n");
sb.append("Host: www.gome.com.cn\r\n");
sb.append("Connection: Close\r\n\r\n");
Socket socket = new Socket("www.gome.com.cn", 80);
OutputStream out = socket.getOutputStream();
out.write(sb.toString().getBytes());
InputStream in = socket.getInputStream();
String line;
while ((line = readLine(in, "UTF-8")).length() != 0) {
System.out.println(line);
}
readLine(in, "UTF-8"); // should always be an empty line
GZIPInputStream gzip = new GZIPInputStream(in);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
int n;
while ((n = gzip.read(buf)) != -1) {
baos.write(buf, 0, n);
}
String content = new String(baos.toByteArray(), "UTF-8");
System.out.println(content);
socket.close();
}