HttpURLConnection学习

@see http://www.blogjava.net/jjshcc/archive/2010/07/21/326762.html

@see http://www.blogjava.net/supercrsky/articles/247449.html

 

URL url = new URL("https://www.douban.com/accounts/login"); 
		HttpURLConnection httpUrlConnection =(HttpURLConnection)  url.openConnection();
		
		httpUrlConnection.setDoOutput(true); 

		// 设置是否从httpUrlConnection读入,默认情况下是true; 
		httpUrlConnection.setDoInput(true); 

		// Post 请求不能使用缓存 
		httpUrlConnection.setUseCaches(false); 

		// 设定传送的内容类型是可序列化的java对象 
		// (如果不设此项,在传送序列化对象时,当WEB服务默认的不是这种类型时可能抛java.io.EOFException) 
		httpUrlConnection.setRequestProperty("Content-type", "application/x-java-serialized-object"); 

		// 设定请求的方法为"POST",默认是GET 
		httpUrlConnection.setRequestMethod("POST"); 
		
		httpUrlConnection.setRequestProperty("Accept","image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, application/x-silverlight, */*");
		httpUrlConnection.setRequestProperty("Referer","http://www.douban.com/accounts/login");
		httpUrlConnection.setRequestProperty("Accept-Language","zh-cn");
		httpUrlConnection.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
		httpUrlConnection.setRequestProperty("Accept-Encoding","gzip, deflate");
		httpUrlConnection.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; InfoPath.1; CIBA)");
		httpUrlConnection.setRequestProperty("Host","www.douban.com");
		httpUrlConnection.setRequestProperty("Content-Length","139");
		httpUrlConnection.setRequestProperty("Connection","Keep-Alive");
		httpUrlConnection.setRequestProperty("Cache-Control","no-cache");
		
		 httpUrlConnection.connect(); 
		 OutputStream outStrm = httpUrlConnection.getOutputStream(); 
		 
//		 DataOutputStream out = new DataOutputStream(connection
//	                .getOutputStream());
//	        // The URL-encoded contend
//	        // 正文,正文内容其实跟get的URL中'?'后的参数字符串一致
//	        String content = "firstname=" + URLEncoder.encode("一个大肥人", "utf-8");
//	        // DataOutputStream.writeBytes将字符串中的16位的unicode字符以8位的字符形式写道流里面
//	        out.writeBytes(content); 
//	     
//	     //现在通过输出流对象构建对象输出流对象,以实现输出可序列化的对象。 
	     String content="source=simple&redir=http%3A%2F%2Fmovie.douban.com%2Fchart&form_email=email&form_password=password&user_login=%E7%99%BB%E5%BD%95";
	     outStrm.write(content.getBytes());
	     outStrm.flush();
	     outStrm.close(); // flush and close

		 InputStream inStrm = httpUrlConnection.getInputStream(); 
		 
		 BufferedReader br = new BufferedReader(new InputStreamReader(inStrm,"gbk"));
		 String temp="";
		 while((temp=br.readLine())!=null){
			 System.out.println(temp);
		 }

你可能感兴趣的:(java)