【java】解决httpurlconnection 乱码

拿到流后如果不指定读取编码方式,就像下面这样:

InputStream is = conn.getInputStream();//拿到输入流  
InputStreamReader isr = new InputStreamReader(is);  
BufferedReader br = new BufferedReader(isr);

得到:

闆嗗洟闂嵎

解决httpurlconnection 乱码:

InputStream is = conn.getInputStream();//拿到输入流  
BufferedReader br = new BufferedReader(new InputStreamReader(is,"utf-8"));

完整代码:

	public static void run(){
		try{
			System.out.println("==================开始了=====================================");

			List list = new ArrayList();
			list.add("http://www.baidu.com");
			list.add("http://.....");

			String subffix = "";
			for (int i = 0; i < list.size(); i++) {
				URL url = new URL(list.get(i) + subffix);

				HttpURLConnection  conn =  (HttpURLConnection )url.openConnection();
				conn.setRequestMethod("GET");  
				conn.setDoInput(true);  
				conn.setDoOutput(true);  
				conn.setInstanceFollowRedirects(true);  
				conn.setRequestProperty("content-type", "text/html");   

				try{
					conn.connect();
				}catch (Exception e) {
					System.out.println("这台"+list.get(i)+"挂了~");
					
					continue;
				}
				InputStream is = conn.getInputStream();//拿到输入流  
				BufferedReader br = new BufferedReader(new InputStreamReader(is,"utf-8"));
				StringBuffer resultBuffer = new StringBuffer();
				String tempLine = null;
				while ((tempLine = br.readLine()) != null) {
					resultBuffer.append(tempLine);
				}
				System.out.println(resultBuffer.toString());  

				br.close();  
				is.close();  
			}
		}catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		run();
	}

==================开始了=====================================
											百度一下,你就知道							


你可能感兴趣的:(Java)