package com.library.util;


import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

public class ClientInternet {

	/**维持Session获得sessionid*/
	public static String GetCookie(String address) {
		String sessionid = address+"?start=yes";
		URL url;
		try {
			url = new URL(address);
			HttpURLConnection con = (HttpURLConnection) url.openConnection();
			// 取得sessionid.
			String cookieval = con.getHeaderField("set-cookie");
			if (cookieval != null) {
				sessionid = cookieval.substring(0, cookieval.indexOf(";"));

			}
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return sessionid;
	}

	/**向服务器获取路径数据*/
	public static String GetData(String address, String sessionid, String list_state) {
		String post=("list_state=" + list_state);
		return OpearConnect(address, sessionid, post);
	}
	
	/**与服务器相连接,参数名称自定（连接地址,SessionId,post参数）*/
	 public static String OpearConnect(String address, String sessionid, String post){
		 String urlpath = address;
			String path = "";
			try {
				URL url = new URL(urlpath);
				HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
				if (sessionid != null) {
					httpcon.setRequestProperty("cookie", sessionid);
				}
				httpcon.setDoInput(true);
				httpcon.setConnectTimeout(50000);
				httpcon.setRequestMethod("POST");
				httpcon.setDoOutput(true);
				httpcon.setRequestProperty("Charset", "UTF-8");
				OutputStream out = httpcon.getOutputStream();
				if(post!=null){
					out.write(post.getBytes("UTF-8"));
				}
				
				out.close();
				if (httpcon.getResponseCode() == 200) {
					InputStreamReader read = new InputStreamReader(httpcon.getInputStream(),"UTF-8");
					BufferedReader buffer = new BufferedReader(read);
					String instring = null;

					while ((instring = buffer.readLine()) != null) {
						path += instring;

					}
					read.close();
					httpcon.disconnect();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return path;
	 }
	/**开辟自主线程来进行访问网络*/
	 public void TheadConnect(String address, String sessionid, String post){
		 new connect(address, sessionid, post).start();
	 }
	 class connect extends Thread{
		 public String address;
		 public String sessionid;
		 public String post;
		 public int agrs=0;
		 public connect(String address, String sessionid, String post){
			 this.address=address;
			 this.post=post;
			 this.sessionid=sessionid;
		 }
		 public void run() {
			String content=OpearConnect(address, sessionid, post);
		}
	 }
	 
		/**
		 * android上传文件到服务器
		 * @param file  需要上传的文件
		 * @return  返回上传地址
		 */
		public static String uploadFile(String address,String sessionid,File file)
		{
			String result = "";//返回上传地址
			String CHARSET = "utf-8"; //设置编码
			String  BOUNDARY =  UUID.randomUUID().toString();  //边界标识   随机生成
			String PREFIX = "--" , LINE_END = "\r\n";
			String CONTENT_TYPE = "multipart/form-data";   //内容类型

			try {
				URL url = new URL(address);
				HttpURLConnection conn = (HttpURLConnection) url.openConnection();
				if (sessionid != null) {
					conn.setRequestProperty("cookie", sessionid);
				}
				conn.setReadTimeout(10*1000);
				conn.setConnectTimeout(10*1000);
				conn.setDoInput(true);  //允许输入流
				conn.setDoOutput(true); //允许输出流
				conn.setUseCaches(false);  //不允许使用缓存
				conn.setRequestMethod("POST");  //请求方式
				conn.setRequestProperty("Charset", CHARSET);  //设置编码
				conn.setRequestProperty("connection", "keep-alive");
				conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary=" + BOUNDARY);

				if(file!=null)
				{
					/**
					 * 当文件不为空，把文件包装并且上传
					 */
					DataOutputStream dos = new DataOutputStream( conn.getOutputStream());
					StringBuffer sb = new StringBuffer();
					sb.append(PREFIX);
					sb.append(BOUNDARY);
					sb.append(LINE_END);
					/**
					 * 这里重点注意：
					 * name里面的值为服务器端需要key   只有这个key 才可以得到对应的文件
					 * filename是文件的名字，包含后缀名的   比如:abc.png
					 */

					sb.append("Content-Disposition: form-data; name=\"file\"; filename=\""+file.getName()+"\""+LINE_END);
					sb.append("Content-Type: application/octet-stream; charset="+CHARSET+LINE_END);
					sb.append(LINE_END);
					dos.write(sb.toString().getBytes("utf-8"));
					InputStream is = new FileInputStream(file);
					byte[] bytes = new byte[1024];
					int len = 0;
					while((len=is.read(bytes))!=-1)
					{
						dos.write(bytes, 0, len);
					}
					is.close();
					dos.write(LINE_END.getBytes());
					byte[] end_data = (PREFIX+BOUNDARY+PREFIX+LINE_END).getBytes();
					dos.write(end_data);
					dos.flush();
					/**
					 * 获取响应码  200=成功
					 * 当响应成功，获取响应的流
					 */
					if (conn.getResponseCode() == 200) {
						InputStreamReader read = new InputStreamReader(conn.getInputStream());
						BufferedReader buffer = new BufferedReader(read);
						String instring = null;

						while ((instring = buffer.readLine()) != null) {
							result += instring;

						}
						read.close();
						conn.disconnect();
					}

				}
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			return result;
		}
	 
	
	/**向服务器发送数据*/
	 public static String SendData(String address, String sessionid,byte [] data ){
		 //发送两个参数path  state
		 String urlpath = address;
		 String path = "";
			try {
				URL url=new URL(urlpath);
				HttpURLConnection httpcon=(HttpURLConnection) url.openConnection();
				if(sessionid != null) { 
					httpcon.setRequestProperty("cookie", sessionid);
					}
//				httpcon.setDoInput(true);
				httpcon.setConnectTimeout(5000);
				httpcon.setRequestMethod("POST");
				httpcon.setDoOutput(true);
//				httpcon.setRequestProperty("Content-Type", "application/octet-stream");  
//				httpcon.setRequestProperty("Connection", "Keep-Alive");// 维持长连接  
				httpcon.setRequestProperty("Charset", "UTF-8");
//				httpcon.setRequestProperty("Content-Length",String.valueOf(data.length));
				OutputStream out=httpcon.getOutputStream();
				out.write(data);
				out.close();
				if(httpcon.getResponseCode()==200){
					InputStreamReader read = new InputStreamReader(httpcon.getInputStream(),"UTF-8");
					BufferedReader buffer = new BufferedReader(read);
					String instring = null;

					while ((instring = buffer.readLine()) != null) {
						path += instring;

					}
					read.close();
					httpcon.disconnect();
				}
				return path;
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				System.out.println("线程------"+e.toString());
				return path;
			}
	 }
	 
	 
	 /**
		 * 使用json数据与服务器交互，获取图片  requestMethod默认为POST
		 * 
		 * @param address 请求地址
		 * @param requestMethod 请求方法（POST或GET）如需其它方式，请自行修改代码
		 * @param json 请求的json数据
		 * @param path 图片存放地址
		 * @return true 成功；false 失败
		 * @author xuwenjun
		 */
		public static boolean OpenConnectForImg(String address, String requestMethod, String json, String path){
			String urlpath = address;
			try {
				URL url = new URL(urlpath);
				HttpURLConnection httpcon = (HttpURLConnection) url.openConnection();
				httpcon.setDoInput(true);
				
				//请求数据为json
				httpcon.setRequestProperty("Content-Type", "application/json");
				//设置请求超时
				httpcon.setConnectTimeout(50000);				
				//设置requestMethod
				if(requestMethod != null)
					httpcon.setRequestMethod(requestMethod);
				else
					httpcon.setRequestMethod("POST");
				
				//若setDoOutput(true)，则setRequestMethod将被修改为POST
				if(httpcon.getRequestMethod().equals("POST")){
					httpcon.setDoOutput(true);
					httpcon.setRequestProperty("Charset", "UTF-8");
					OutputStream out = httpcon.getOutputStream();
					if(json!=null){
						out.write(json.getBytes("UTF-8"));
					}					
					out.close();
				}else{
					httpcon.setDoOutput(false);
					httpcon.setRequestProperty("Charset", "UTF-8");
				}
				
				//返回结果
				if (httpcon.getResponseCode() == 200) {
					File file=new File(path);
					if(!file.exists()){
						file.createNewFile();
					}
					InputStream read = httpcon.getInputStream();
					FileOutputStream fo = new FileOutputStream(file);
					byte[] buf = new byte[1024];  
	                int length = 0;  
	                System.out.println("开始下载:" + url);  
	                while ((length = read.read(buf, 0, buf.length)) != -1) {  
	                    fo.write(buf, 0, length);  
	                }  
	                read.close();  
	                fo.close();
					httpcon.disconnect();
					return true;
				}
			} catch (IOException e) {
				e.printStackTrace();
				return false;
			}
			return false;
		 }

}
