LinuxEye - Linux系统教程

LinuxEye - Linux系统教程

当前位置: 主页 > 脚本编程 >

php中curl类常用方法封装和详解

时间:2012-06-22 18:41来源:oschina 编辑:admin 点击:
curl对于PHP开发这来说是经常用到的一个类. 在抓取远程文件或是内容的时候就更常用了. 不过原生态的curl类比较复杂, 尤其对于新手来说,很多参数很容易让人头晕,现在好了. 这个类是封
curl对于PHP开发这来说是经常用到的一个类. 在抓取远程文件或是内容的时候就更常用了. 不过原生态的curl类比较复杂, 尤其对于新手来说,很多参数很容易让人头晕,现在好了. 这个类是封装了几个常用的curl函数. 可以实现抓取远程文件,模拟提交数据等功能.
package cn.captain.html;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class htmlRequest {
		/**
		 * @param args
		 * @throws MalformedURLException 
		 */
		public static void main(String[] args) throws Exception
		{
			URL url = new URL("http://www.baidu.com/"); 
			HttpURLConnection conn = (HttpURLConnection)url.openConnection();
			conn.setRequestMethod("GET");
			conn.setConnectTimeout(5 * 1000);
			InputStream inStream =  conn.getInputStream();//通过输入流获取html数据	
			byte[] data = readInputStream(inStream);//得到html的二进制数据
			String html = new String(data);
			System.out.println(html);
		}
	   public static byte[] readInputStream(InputStream instream) throws Exception
	    {
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			byte[]  buffer = new byte[1204];
			int len = 0;
			while ((len = instream.read(buffer)) != -1)
			{
				outStream.write(buffer,0,len);
			}
			instream.close();
			return outStream.toByteArray();     	
		}

	}

转载请保留固定链接: https://linuxeye.com/program/599.html

------分隔线----------------------------
标签:phpcurl封装
栏目列表
推荐内容