单例简单快速写法HttpUtil举例_JAVA_编程开发_程序员俱乐部

中国优秀的程序员网站程序员频道CXYCLUB技术地图
热搜:
更多>>
 
您所在的位置: 程序员俱乐部 > 编程开发 > JAVA > 单例简单快速写法HttpUtil举例

单例简单快速写法HttpUtil举例

 2018/11/1 12:18:48  andyou2012  程序员俱乐部  我要评论(0)
  • 摘要:publicclassHttpUtil{privatestaticHttpUtilutil;publicstaticHttpUtilgetInstence(){if(util==null){util=newHttpUtil();}returnutil;}publicStringpost(Stringpath,Stringheader,Stringparam){PrintWriterout=null;BufferedReaderin=null;Stringresult="";try
  • 标签:HTTP
class="java">
public class HttpUtil {

	private static HttpUtil util;

	public static HttpUtil getInstence() {
		if (util == null) {
			util = new HttpUtil();
		}
		return util;
	}

	public String post(String path, String header, String param) {

		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";

		try {
		
			URL url = new URL(path);
			URLConnection conn = url.openConnection();

			conn.setRequestProperty("Accept-Charset", "UTF-8");  
			conn.setRequestProperty("contentType", "UTF-8");  
			conn.setRequestProperty("Content-Type", "text/plain");
			conn.setConnectTimeout(60*1000);
			conn.setReadTimeout(60*1000);
			conn.setDoOutput(true);
			conn.setDoInput(true);

			if(header != null && header.trim().length() > 0){
				String keyValues[] = header.split(";");
				for(int i=0;keyValues!=null&&i<keyValues.length;i++){
					String keyValue = keyValues[i];
					String data[] = keyValue.split(":");
					conn.setRequestProperty(data[0], data[1]);
				}
			}
			
			out = new PrintWriter(new OutputStreamWriter(conn.getOutputStream(), "utf-8"));
			if (param != null) {
				out.print(param);
			}
			out.flush();
			in = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}

			return result;
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				ex.printStackTrace();
			}
		}

		return null;
	}
	
	

}
发表评论
用户名: 匿名