package com.backfire.php;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;

public class URLUtil {
	public static String getRequestStr(String urlStr) {
		String inputLine = "";
		URL url = null;
		HttpURLConnection urlConnection = null;
		try {
			url = new URL(urlStr);
			urlConnection = (HttpURLConnection) url.openConnection();
			BufferedReader in = new BufferedReader(new InputStreamReader(
					urlConnection.getInputStream()));
			String str = null;
			while ((str = in.readLine()) != null) {
				inputLine += str;
			}
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (urlConnection != null) {
				urlConnection.disconnect();
			}
		}
		return inputLine;
	}

	public static String getPostRequestStr(String urlStr, String param) {
		String inputLine = "";
		URL url = null;
		PrintWriter out = null;
		HttpURLConnection urlConnection = null;
		try {
			url = new URL(urlStr);
			urlConnection = (HttpURLConnection) url.openConnection();
			urlConnection.setDoOutput(true);
			urlConnection.setDoInput(true);
			urlConnection.setRequestMethod("POST");
			urlConnection.setConnectTimeout(10000);//连接超时 单位毫秒
	        urlConnection.setReadTimeout(2000);//读取超时 单位毫秒
			out = new PrintWriter(urlConnection.getOutputStream());
			out.print(param);
			out.flush();

			BufferedReader in = new BufferedReader(new InputStreamReader(
					urlConnection.getInputStream()));
			String str = null;
			while ((str = in.readLine()) != null) {
				inputLine += str;
			}
			in.close();			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (urlConnection != null) {
				urlConnection.disconnect();
			}
		}
		return inputLine;
	}
	
	public static String postRequestStr(String urlStr, String param, String charSet) throws Exception {
		String inputLine = "";
		URL url = new URL(urlStr);
		HttpURLConnection urlConnection = null;
		PrintWriter out;
		try {
			url = new URL(urlStr);
			urlConnection = (HttpURLConnection) url.openConnection();
			urlConnection.setDoOutput(true);
			urlConnection.setDoInput(true);

			out = new PrintWriter(urlConnection.getOutputStream());
			out.print(param);
			out.flush();

			BufferedReader in = new BufferedReader(new InputStreamReader(
					urlConnection.getInputStream(), charSet));
			String str = null;
			while ((str = in.readLine()) != null) {
				inputLine += str;
			}
			in.close();			
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (urlConnection != null) {
				urlConnection.disconnect();
			}
		}
		return inputLine;
	}

	public static String URLEncoder(String param) {
		try {
			param = java.net.URLEncoder.encode(param, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return "";
		}
		return param;
	}
}