1. 程式人生 > >GET方式從伺服器獲取資料

GET方式從伺服器獲取資料

<span style="font-size:18px;">import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import org.apache.http.client.ClientProtocolException;
//從伺服器獲取資料
public class HttpUtils1
{
	public static void main(String[] args) throws ClientProtocolException, IOException
	{
		String path = "http://localhost:8080/day01";
		InputStream in = HttpUtils2.getInputStream(path);
		System.out.println(HttpUtils2.getResult(in, "utf-8"));		
	}
	//得到能獲取伺服器資料的讀取流
	public static InputStream getInputStream(String path) throws IOException
	{
		URL url = new URL(path);
		HttpURLConnection con = (HttpURLConnection) url.openConnection();
		
		con.setRequestMethod("GET");
		con.setConnectTimeout(5000);
		con.setDoInput(true);
		
		InputStream in =null;
		if(con.getResponseCode()==200)
		{
			in = con.getInputStream();
		}
		return in;
	}
	//通過讀取流把伺服器資料讀到本地記憶體
	public static String getResult(InputStream in,String code) throws IOException
	{
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		byte[] b = new byte[1024];
		int len=0;
		while((len=in.read(b))!=-1)
		{
			baos.write(b,0,len);
		}
		return new String(baos.toByteArray(),code);
	}
	
}
</span>