HTTP請求讀流時偶爾會出現亂碼

最近遇到一個問題,向服務器請求數據,然後將流讀出來

不過,有時候讀出來的數據裏面會有亂碼(/ □ \)

之前讀流的方式是這樣的

	public static String getString(InputStream inputStream){
		StringBuffer buffer = new StringBuffer();
		if(inputStream != null){
			byte[] b = new byte[4096];
			try {
				for (int n; (n = inputStream.read(b)) != -1;) {
					buffer.append(new String(b, 0, n));
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return buffer.toString();
	}

最後將讀流方式是這樣的

	public static String getString(InputStream inputStream){
		ByteArrayOutputStream outSteam = new ByteArrayOutputStream();  
        try {
			byte[] buffer = new byte[1024];  
			int len = -1;  
			while ((len = inputStream.read(buffer)) != -1) {  
			    outSteam.write(buffer, 0, len);  
			}  
			outSteam.close();
			inputStream.close();
		} catch (IOException e) {
			e.printStackTrace();
		}  
        return new String(outSteam.toByteArray());
	}

問題解決了,至少是到現在沒出現問題

姑且在這裏記錄一下

發佈了43 篇原創文章 · 獲贊 3 · 訪問量 23萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章