package com.example.httpurl;


import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

	public Button send;
	public Button sendWithTask;
	private static final String TAG = "myLogs";
	public MyTask mt;
	public LoginVK vkLogin;
	public String result_string = "";
	public HttpURLConnection urlConnection;
	public OutputStreamWriter request = null; 
	public String aString;
	public String responseMsg;
	public StringBuffer data = new StringBuffer();
	public StringBuffer DATA_VK_LOGIN = new StringBuffer();
	public String ip_h = "", to = "";
	public URLConnection connection = null;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		
		send = (Button) findViewById(R.id.send);
		sendWithTask = (Button) findViewById(R.id.sendWithTask);
		
		OnClickListener oclBtn = new OnClickListener() 
		{
			@Override
			public void onClick(View v) 
			{
				 //  id  ,   
                switch (v.getId()) {
                case R.id.send:
                  //  
                  Log.d(TAG, "  ");
                  testFunc();
                  break;
                case R.id.sendWithTask:
                  //  Cancel
                	Log.d(TAG, "  Cancel");
                	testFunc();
                  break;
                }
				
			}
		};
		send.setOnClickListener(oclBtn);
		sendWithTask.setOnClickListener(oclBtn);
	}
	
	public void testFunc (){
		mt = new MyTask();
	    mt.execute();
	    Log.d(TAG, " MyTask()");
	}
	
	// ip_h. 
	//         !!!
	  class MyTask extends AsyncTask<Void, Integer, String> {
		  
		 
		  
		  
		  @Override
		    protected String doInBackground(Void... params) {
			  StringBuffer requestBody = new StringBuffer();
			  
			try {
				Log.d(TAG, "  : http://oauth.vk.com");
			URLConnection connection = null;
			String myString = "";
            URL url = new URL("http://oauth.vk.com/authorize?client_id=3066711&scope=friends&redirect_uri=http://oauth.vk.com/blank.html&display=page&response_type=token");
            connection = url.openConnection();
            HttpURLConnection httpConnection = (HttpURLConnection) connection;
            httpConnection.setRequestMethod("POST");
            httpConnection.setUseCaches(false);
            httpConnection.setDoOutput(true);
            httpConnection.setDoInput(true);
            httpConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:10.0.2) Gecko/20100101 Firefox/10.0.2");
            httpConnection.setRequestProperty("Accept-Charset","utf-8");
            httpConnection.setRequestProperty("Accept-Encoding", "identity");
            httpConnection.setRequestProperty("Referer", "http://vk.com/");
            httpConnection.setRequestProperty("Connection", "keep-alive");
            httpConnection.setRequestProperty("Content-Type", "text/html");
            requestBody.append(myString); //     Post
            // 
            httpConnection.connect();
            //  
            DataOutputStream dataOS = new DataOutputStream(httpConnection.getOutputStream());
            dataOS.writeUTF(myString.toString()); 
        
            //   
            int responseCode = httpConnection.getResponseCode();
            
            if (responseCode == 200) { //    (200),  
                InputStream in = httpConnection.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, "windows-1251");
                
                //  Set-Cookie:
                //   ,     !!!!
                Log.d(TAG, "Content-Type: " + httpConnection.getHeaderField("Content-Type"));
                List<String> cookies = connection.getHeaderFields().get("Set-Cookie");
                
                int cookies_size = cookies.size();
                
                try {
                	while (cookies_size > 0) {
                    Log.d(TAG, "Set-Cookie: " + cookies.get((cookies_size - 1)));
                    cookies_size--;
                }
                } catch(Exception e) {
                	Log.d(TAG,  "Exception:" + e.getMessage());
                }
                               
                int c;
                while ((c = isr.read()) != -1) 
                {  
                	data.append((char) c);  
                }
                
                // 
                //Log.d(TAG, "/************ **************/");
                //    
                String new_data = data.toString();
                int index_ip_h;
                index_ip_h = new_data.indexOf("ip_h=");
                index_ip_h = index_ip_h + 5;
                ip_h = new_data.substring(index_ip_h, index_ip_h + 18);
                //Log.d(TAG, "ip_h: " + ip_h);
                //Log.d(TAG, "/*********  ************/");
            } else {
            	Log.d(TAG, "Server is unavailable.\nPlease try again."); 
            		}
            dataOS.flush();
            dataOS.close();
            httpConnection.disconnect();
             
   
			} catch (MalformedURLException e) { 
				Log.d(TAG, "MalformedURLException: " + e.getMessage()); 
				} catch (IOException e) {
					Log.d(TAG,  "IOException: " + e.getMessage()); 
					
				} catch (Exception e) {
					Log.d(TAG,  "Exception: " + e.getMessage());  
				}
               
		return data.toString();
		  }

		    @Override
		    protected void onPostExecute(String data) {
		    	//Log.d(TAG, data.toString());
		      Log.d(TAG, " ");
		      
		     vkLogin = new LoginVK();
		    vkLogin.execute();
			    Log.d(TAG, " LoginVK()");
		         
		      }
		  }
	  
	  
	  class LoginVK extends AsyncTask<Void, Void, String> {
			 
		  StringBuffer requestBody = new StringBuffer();
				 
		  protected String doInBackground(Void... urls) {
		      try {
		    	  
		    	  URLConnection connectionVK = null;
					
		          //  http://login.vk.com/!!
		    	  Log.d(TAG, "  : http://login.vk.com");
		          String email = "email@email.com";
		          String pass = "PASSWORD";
		          String myString = "act=login&role=al_frame&expire=&captcha_sid=&captcha_key=&_origin=http://vk.com&ip_h=" 
		        		  + ip_h 
		        		  + "&email=" + email 
				          + "&pass=" + pass;
		          
		          URL url_login_vk = new URL("http://login.vk.com/?act=login");
		          connectionVK = url_login_vk.openConnection();
		          HttpURLConnection httpConnection_login_vk = (HttpURLConnection) connectionVK;
		          httpConnection_login_vk.setUseCaches(false);
		          httpConnection_login_vk.setDoOutput(true);
		          httpConnection_login_vk.setDoInput(true);
		          httpConnection_login_vk.setRequestProperty("Accept", "*/*");
		          httpConnection_login_vk.setRequestProperty("Referer", "http://vk.com/login?act=mobile");
		          httpConnection_login_vk.setRequestProperty("Content-Type", "text/html");
		          httpConnection_login_vk.setRequestProperty("User_Agent", "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)");
		          httpConnection_login_vk.setRequestMethod("POST");
		          httpConnection_login_vk.setRequestProperty("Accept-Encoding", "gzip,deflate");
		          httpConnection_login_vk.setRequestProperty("Connection", "keep-alive");
		          httpConnection_login_vk.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
		          
		          requestBody.append(myString); //     Post
		            // 
		          httpConnection_login_vk.connect();
		            //  
		            DataOutputStream dataVK = new DataOutputStream(httpConnection_login_vk.getOutputStream());
		            dataVK.writeBytes(myString); 
		         
		          //Log.d(TAG, "Content-Type: " + httpConnection_login_vk.getHeaderField("Content-Type"));
		          //Log.d(TAG, "Location: " + httpConnection_login_vk.getHeaderField("Location"));
	                List<String> cookies = connectionVK.getHeaderFields().get("Set-Cookie");
	                
	                int cookies_size = cookies.size();
	                
	                try {
	                	while (cookies_size > 0) {
	                    //Log.d(TAG, "Set-Cookie: " + cookies.get((cookies_size - 1)));
	                    cookies_size--;
	                }
	                } catch(Exception e) {
	                	Log.d(TAG,  "Exception: " + e.getMessage());
	                }
		          
		          
		           dataVK.flush();
		          dataVK.close();
		          httpConnection_login_vk.disconnect();
		          
		          ////*************************/////////////////////////****************//////////////////
		          Log.d(TAG, "  : http://vk.com/login");
		          String postVkCom = httpConnection_login_vk.getHeaderField("Location");
		          
		          url_login_vk = new URL(postVkCom);
		          connectionVK = url_login_vk.openConnection();
		          HttpURLConnection httpConn_vk_login = (HttpURLConnection) connectionVK;
		          httpConn_vk_login.setUseCaches(false);
		          httpConn_vk_login.setDoOutput(true);
		          httpConn_vk_login.setDoInput(true);
		          //while (cookies_size > 0) {
		        	//  httpConn_vk_login.setRequestProperty("Cookie", cookies.get((cookies_size - 1)));
		        	 // cookies_size--;
	               // }
		          httpConn_vk_login.setRequestProperty("Accept", "*/*");
		          httpConn_vk_login.setRequestProperty("Referer", "http://vk.com/login?act=mobile");
		          httpConn_vk_login.setRequestProperty("Content-Type", "text/html");
		          httpConn_vk_login.setRequestMethod("GET");
		          httpConn_vk_login.setRequestProperty("Accept-Encoding", "gzip,deflate");
		          httpConn_vk_login.connect();
		           
		          dataVK = new DataOutputStream(httpConn_vk_login.getOutputStream());
		          
		          InputStream IS_VK_LOGIN = httpConn_vk_login.getInputStream();
	              InputStreamReader ISR_VK_LOGIN = new InputStreamReader(IS_VK_LOGIN, "windows-1251");
	              
	              
	              int c;
	                while ((c = ISR_VK_LOGIN.read()) != -1) 
	                {  
	                	DATA_VK_LOGIN.append((char) c);  
	                }  
	                
	              Log.d(TAG, ": " + DATA_VK_LOGIN.length());
	              Log.d(TAG, "Content-Type: " + httpConn_vk_login.getHeaderField("Content-Type"));
		          dataVK.flush();
		          dataVK.close();
		          httpConn_vk_login.disconnect();
		            
		          ////*************************/////////////////////////****************//////////////////
		          
		    	  
		       
		      } catch (MalformedURLException e) { 
					Log.d(TAG, "MalformedURLException: " + e.getMessage()); 
					} catch (IOException e) {
						Log.d(TAG,  "IOException: " + e.getMessage()); 
						
					} catch (Exception e) {
						Log.d(TAG,  "Exception: " + e.getMessage());  
					}
		    
			String pass = "!";
			return pass;
		    }
	  
		  @Override
		    protected void onPostExecute(String pass) {
		    //Log.d(TAG, pass);
		      Log.d(TAG, " ");
		      
		         
		      }
	  
	  }
}