package com.example.http;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.AbstractHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import com.example.utils.ParseHtml;
/**
 * 封装了连接网络的Ip，用HttpClient发送Post请求
 * 抓取网页
 * @author 超超boy
 *
 */
public class HttpUtils {

    private static HttpClient httpClient;
    private static List<Cookie> cookies;  
   // private static Context context;
	public HttpUtils() {
         this.httpClient=  new DefaultHttpClient();
	}
   public static String sendPostMessage(Map<String,String> map,String encode){
	   String path = "http://202.118.88.140/loginAction.do";
	   List<NameValuePair> list = new ArrayList<NameValuePair>();
	   if(map != null && !map.isEmpty()){
		   for(Map.Entry<String, String> entry: map.entrySet()){ //迭代器
			   //键值对
			   NameValuePair nameValuePair = new BasicNameValuePair(entry.getKey(), entry.getValue());
			   list.add(nameValuePair);
		   }
	   }
	  try {
		  //实现将请求的参数封装到表单中，
		  HttpEntity entity = new UrlEncodedFormEntity(list ,encode);//HttpEntity
		//使用post方式提交数据
		HttpPost post = new HttpPost(path);
		post.setEntity(entity);//请求体中
		//默认客户端
		HttpClient client = httpClient;
		
		HttpResponse httpResponse = client.execute(post);
		if(httpResponse.getStatusLine().getStatusCode() == 200){
			 // 获取返回的cookie  
	        cookies = ((AbstractHttpClient) client).getCookieStore().getCookies();
	        for(int i=0; i< cookies.size();i++ ){
	        	System.out.println("...................................");
	        	System.out.println("name:"+cookies.get(i).getName());//09-10 09:08:51.890: I/System.out(24503): name:JSESSIONID
                 //09-10 09:08:51.890: I/System.out(24503): getComment:null
	        	System.out.println("getComment:"+cookies.get(i).getComment());
	        	//09-10 09:08:51.890: I/System.out(24503): getValue:febr_8qMVGnZFbh49X0_u
	        	System.out.println("getValue:"+cookies.get(i).getValue());
	        }
			HttpEntity httpEntity = httpResponse.getEntity();
			InputStream inputStream = httpEntity.getContent();
			return changeInputeStream(inputStream, encode);
		}
	} catch (UnsupportedEncodingException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (ClientProtocolException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	 
	   return "";
   }
   
   /**
	 * 学期课表
	 * @param encode
	 * @return
	 */
	public static String sendGetXueQiKeBiao(String encode){
       InputStream inputStream = null;
		String URL_PATH="http://202.118.88.140/xskbAction.do?actionType=1";
		
			HttpGet httpGet = new HttpGet(URL_PATH);
			HttpClient httpClient = new DefaultHttpClient();
			httpGet.setHeader("Cookie",cookies.get(0).getName()+"="+ cookies.get(0).getValue());  
			try {
				HttpResponse response = httpClient.execute(httpGet);
				if(response.getStatusLine().getStatusCode() == HttpURLConnection.HTTP_OK){
					HttpEntity httpEntity = response.getEntity();
					 inputStream = httpEntity.getContent();
					return changeInputeStream(inputStream, encode);
				}
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IllegalStateException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		
		return "";
	}
   /**
    * 将一个输入流转换成字符串
    * @param inputStream
    * @param encode
    * @return
    */
   public static String changeInputeStream(InputStream inputStream,String encode) {
       //通常叫做内存流，写在内存中的
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		byte[] data = new byte[1024];
		int len = 0;
		String result = "";
		if(inputStream != null){
			try {
				while((len = inputStream.read(data))!=-1){
					//data.toString();
					outputStream.write(data, 0, len);
				}
				//result是在服务器端设置的doPost函数中的
				result = new String(outputStream.toByteArray(),encode);
				outputStream.flush();
				outputStream.close();
				inputStream.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return result;
	}
    /**
     * 
     * @param id  学号
     * @param pwd 密码
     * @return
     */
	public static String set(String id,String pwd) {
		// TODO Auto-generated method stub
		Map<String, String> map = new HashMap<String, String>();
		map.put("mm", pwd);
		map.put("zjh", id);
		String result = HttpUtils.sendPostMessage(map, "gb2312");
		
		System.out.println("result:"+ result); //返回网页内容，成功
		result = sendGetXueQiKeBiao("gb2312");
		System.out.println("-----------------------------------------------"); //返回网页内容，成功
		//System.out.println("result:"+ result); //返回课表内容，成功
		
		return result;
	}

}
