1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
| package com.example.demo;
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader;
import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils;
public class Main {
public static void main(String[] args) throws IOException { try (CloseableHttpClient httpClient = HttpClients.custom().disableAutomaticRetries().build()) { HttpPost httpPost = new HttpPost("http://www.baidu.com");
try (CloseableHttpResponse response = httpClient.execute(httpPost)) { int statusCode = response.getStatusLine().getStatusCode(); InputStream inputStream = response.getEntity().getContent(); readByChars(inputStream);
InputStreamReader inputStreamReader = new InputStreamReader(inputStream); readWithBufferedReader(inputStreamReader); if (statusCode != 200) { final HttpEntity entity = response.getEntity(); final String result = EntityUtils.toString(entity);
System.out.println(result); } } }
}
public static void readByChars(InputStream inputStream) {
InputStreamReader reader = null;
try { System.out.println("以字符为单位读取文件内容,一次读多个字节:"); char[] tempchars = new char[30]; int charread = 0; reader = new InputStreamReader(inputStream); while ((charread = reader.read(tempchars)) != -1) { for (int i = 0; i < charread; i++) { if (tempchars[i] != '\r') { System.out.print(tempchars[i]); } } }
} catch (Exception e1) { e1.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { } } } }
public static void readWithBufferedReader(InputStreamReader inputStreamReader) { BufferedReader reader = null; try { reader = new BufferedReader(inputStreamReader); String tempString = null; int line = 1; while ((tempString = reader.readLine()) != null) { System.out.println("line " + line + ": " + tempString); line++; } reader.close(); } catch (IOException e) { e.printStackTrace(); } finally { if (reader != null) { try { reader.close(); } catch (IOException e1) { } } } }
}
|